I am a beginner in Yii framework. I wanted to have a popup in my createform that links from my other table. The purpose of this is I have a dropbox, If there is no data that is I wanted to pick. I will create first. I want to have a popupbox in my table 1 create.php that will get the create form in my table 2. here is what I started. what seems to be the problem here?
here is my codes for table1 create.php
<?php echo CHtml::link('New Day',"",
array(
'style'=>'cursor:pointer; text-decoration:underline;',
'onClick'=>"{doDay(); $('#dialogDay).dialog('open');}"));?>
<?php
$this->beginWidget('zii.Widgets.jui.CJuiDialog',array(
'id'=>'dialogDay',
'options'=>array(
'title'=>'Add New Day',
'autoOpen'=>false,
'modal'=>true,
'width'=>550,
'height'=>470,
),
));
?>
<div class="divForForm"></div>
<?php $this->endWidget();?>
<script type="text/javascript">
function doDay()
{
<?php echo CHtml::ajax(array(
'url'=>array('day/NewDay'),
'data'=>"js:$(this).serialize()",
'type'=>'post',
'dataType'=>'json',
'success'=>"function(data)
{
if(data.status == 'failure')
{
$('#dialogDay div.divForForm').html(data.div);
$('#dialogDay div.divForForm form').submit(doDay);
}
else
{
window.location.href = ".Yii::app()->getBaseUrl().";
}
}",
))?>
return false;
}
</script>
in my table 2 controller
public function actionNewDay()
{
$model= new Day;
if(isset($_POST['ajax']) && $_POST['ajax']=='day-form')
{
$model->attributes=$_POST['Day'];
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['Day']))
{
$model->attributes=$_POST['Day'];
$name=$model->name;
$mon=$model->mon;
$tue=$model->tue;
$wed=$model->wed;
$thurs=$model->thurs;
$fri=$model->fri;
$sat=$model->sat;
$sun=$model->sun;
$dayassign = new DayAssign();
if($model->save())
{
$dayassign->varName = $name;
$dayassign->varMon = $mon;
$dayassign->varTue = $tue;
$dayassign->varWed = $wed;
$dayassign->varThurs = $thurs;
$dayassign->varFri = $fri;
$dayassign->varSat = $sat;
$dayassign->varSun = $sun;
if($dayassign->save())
{
if(Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'success',
));
}
else{
$url = Yii::app()->getBaseUrl();
Yii::app()->getRequest()->redirect($url);
}
}
}
if(Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'failure',
'div'=>$this->renderPartial('day',array('model'=>$model),true)));
exit;
}
else
$this->render('day',array('model'=>$model,));
}
}
Did it by myself. here is the codes.
Scenario
I have a day model which contains shift eg. Night,Morning that is selected by my EmpSched model. Lets assume that the EmpSched wants to choose the Afternoon Shift but the day model doesnt have afternoon model yet, He will have to create a day first and lose the already inserted input.
We want to allow the user to create the day from the form of the empsche, without changing pages
This is what I done.
in my Day Controller:
public function actionCreate()
{
$model=new Day;
// Uncomment the following line if AJAX validation is needed
//$this->performAjaxValidation($model);
if(isset($_POST['Day']))
{
$model->attributes=$_POST['Day'];
if($model->save())
{
if(Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'success',
'div'=>"Day successfully added"
));
exit;
}
else
$this->redirect(array('view','id'=>$model->id_day));
}
}
if(Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'failure',
'div'=>$this->renderPartial('_form',array('model'=>$model),true)));
exit;
}
$this->render('create',array(
'model'=>$model,
));
}
and in my EmpSched _form.php:
</div>
<?php echo CHtml::link('Create day', "", // the link for open the dialog
array(
'style'=>'cursor: pointer; text-decoration: underline;',
'onclick'=>"{addDay(); $('#dialogDay').dialog('open');}"));?>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog
'id'=>'dialogDay',
'options'=>array(
'title'=>'Create Day',
'autoOpen'=>false,
'modal'=>true,
'width'=>550,
'height'=>470,
),
));?>
<div class="divForForm"></div>
<?php $this->endWidget();?>
<script type="text/javascript">
// here is the magic
function addDay()
{
<?php echo CHtml::ajax(array(
'url'=>array('day/create'),
'data'=> "js:$(this).serialize()",
'type'=>'post',
'dataType'=>'json',
'success'=>"function(data)
{
if (data.status == 'failure')
{
$('#dialogDay div.divForForm').html(data.div);
// Here is the trick: on submit-> once again this function!
$('#dialogDay div.divForForm form').submit(addDay);
}
else
{
$('#dialogDay div.divForForm').html(data.div);
setTimeout(\"$('#dialogDay').dialog('close') \",3000);
}
} ",
))?>
return false;
}
</script>
I hope ill help someone who is on my own boat.
Related
my coding is all about
1)fetch the data from mysql thro php
2)get data from php to d3 based on input by using PHP URL
I want to set alert when the text in the input field is not found in mysql database..
now when I try with the word other than mysql data, it shows
this console
how can i alert when wrong word(other than mysql database value) is submitted
HTML FORM
<form name="editorForm">
<input type="text"name="editor" id="editor"
onchange="document.getElementById('editorForm').submit();">
<input type="submit"value="butn">
</form>
JQUERY TO FETCH THE DATA FROM PHP BASED ON URL
$(function () {
$('form').submit(function (e) {
e.preventDefault();
var t=$('form').serialize();
var u='http://localhost:8888/saff/indexi.php?'+t;
if(u==null){
alert("not found");
}
else{
funn();
}
D3 CODES
function funn(){
d3.json(u, function(treeData) {
//D3 CODES
});
}
my php code
<?php
$con=mysqli_connect("localhost","root","admin","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql="SELECT * FROM phptab where value LIKE '%".$name."%'";
$r = mysqli_query($con,$sql);
$data = array();
while($row = mysqli_fetch_assoc($r)) {
$data[] = $row;
}
function buildtree($src_arr, $parent_id = 0, $tree = array())
{
foreach($src_arr as $idx => $row)
{
if($row['parent'] == $parent_id)
{
foreach($row as $k => $v)
$tree[$row['id']][$k] = $v;
unset($src_arr[$idx]);
$tree[$row['id']]['children'] = buildtree($src_arr, $row['id']);
}
}
ksort($tree);
return $tree;
}
function insertIntoNestedArray(&$array, $searchItem){
if($searchItem['parent'] == 0){
array_push($array, $searchItem);
return;
}
if(empty($array)){ return; }
array_walk($array, function(&$item, $key, $searchItem){
if($item['id'] == $searchItem['parent']){
array_push($item['children'], $searchItem);
return;
}
insertIntoNestedArray($item['children'], $searchItem);
}, $searchItem);
}
$nestedArray = array();
foreach($data as $itemData){
//$nestedArrayItem['value'] = $itemData['value'];
$nestedArrayItem['id'] = $itemData['id'];
$nestedArrayItem['name'] = $itemData['name'];
$nestedArrayItem['parent'] = $itemData['parent'];
$nestedArrayItem['tooltip'] = $itemData['tooltip'];
$nestedArrayItem['color'] = $itemData['color'];
$nestedArrayItem['level'] = $itemData['level'];
$nestedArrayItem['children'] = array();
//$data[]=$dat;
insertIntoNestedArray($nestedArray, $nestedArrayItem);
}
header('Content-Type: application/json');
$json= json_encode($nestedArray,JSON_UNESCAPED_UNICODE);
echo $json = substr($json, 1, -1);
?>
works as expected when the word used is exist in the database
and the page looks like this
getting correct json format in the mozilla console.but design is not shown in the page...but in chrome ,everything works fine..
You need to test if the page is empty in the json function of the d3
function funn(){
d3.json(u, function(treeData) {
if(!treeData.length){
alert("not found");
}else {
//D3 CODES
}
});
}
Make sure that you return a empty object from the page when not found
I want to Show My data in Popup,Once User Selected Department Showing that
Staff's names related to user Selected Department using Ajax,Geeting
data's Correctly But Am showing that Staff's names in Eselect2 Widget
Multiple option in Yii,that Eselect2 Design Not coming Its showing normal
Select Dropdown user Choose multiple choice using ctrl Keys .
My Codings, in that Div staff I am showing that eselect2 widget data's.
Ajax Coding
<div id ="staffs></div>
function selectstaff(id)
{
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("user/users/ajaxselectstaff"); ?>',
data: 'id=' + id,
success: function (packages) {
$('#staffs').html(packages);
}
});
}
Controller Coding
public function actionAjaxselectstaff() {
$id = Yii::app()->request->getPost('id');
$model = Users::model()->getAllStaffDepartment($id);
$this->renderPartial('ajaxselect', array('model' => $model));
}
MOdel Coding,
public function getAllStaffDepartment($id, $type = '') {
$model = UserAccount::model()->findAll('department_code=:id', array(':id' => $id));
$userid = "";
$result = "";
if (isset($model)) {
foreach ($model as $data) {
$userid .= $data->user_id . ",";
}
}
$userid = trim($userid, ',');
if ($userid != "") {
$criteria = new CDbCriteria();
$criteria->condition = "user_role_id!=" . Yii::app()->mconstant->CONST_FIVE . " AND user_role_id!= " . Yii::app()->mconstant->CONST_SIX . " AND user_role_id!= " . Yii::app()->mconstant->CONST_NINE . " AND user_id IN (" . $userid . ")";
$result = Users::model()->findAll($criteria);
$data = CHtml::listData($result, 'user_id', 'real_name');
return $data;
} else {
return false;
}
}
Ajaxselect page:
<?php
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
if ($model) {
?>
<?php
$this->widget('ext.select2.ESelect2', array(
'name' => 'users',
'id' => 'users',
'data' => $model,
'htmlOptions' => array(
'multiple' => true,
'placeholder' => 'Select Users',
),
));
?>
<?php
} else {
echo "No Staff's Found";
}
?>
what's wrong in my code ? Am changes the page to render eselect2 widget design getting properly but render partial eselect2 design not getting,
There is small change in controller which is mention below.
public function actionAjaxselectstaff() {
$id = Yii::app()->request->getPost('id');
$model = Users::model()->getAllStaffDepartment($id);
$this->renderPartial('ajaxselect', array('model' => $model) ,false , true);
}
Please find description of third and forth paramerter of renderPartial in below link : http://www.yiiframework.com/doc/api/1.1/CController#renderPartial-detail
i have a small doubt.. i posted my delete.php page coding here.
if(isset($_GET["id"]))
{
$meal_query = mysql_query("DELETE FROM ebmealplans WHERE MealPlanID = '$id'");
echo mysql_error();
$room_query = mysql_query("DELETE FROM ebroomtypes WHERE RoomTypeID = '$id'");
echo mysql_error();
$tariff_query = mysql_query("DELETE FROM ebvouchertariffs WHERE VoucherID_Fk = '$id'");
echo mysql_error();
$query = mysql_query("DELETE FROM ebvouchers WHERE VoucherID = '$id'");
echo mysql_error();
if($query)
{
echo "<script> alert('Voucher deleted successfully'); </script>";
}
else
{
echo "<script> alert('Failed to delete this voucher'); </script>";
}
mysql_close($link);
echo "<script> location.href='managevouchers.php'; </script>";
}
here i am delete some user datas using this php coding. it worked perfectly. i created four separate tables for store the records. if deletion function was successfully completed i want to show the alert message to users "Deleted Successfully". you can see in my coding i'm just show the alert message for only one $query. i tried another method..
if($query)
{
alert function
}
else
{
alert function
}
if($meal_query)
{
alert function
}
else
{
alert function
}
if($room_query)
{
alert function
}
else
{
alert function
}
if($tariff_query)
{
alert function
}
else
{
alert function
}
it show the alert message four times. i know multiple alert functions annoying the users. my question is how to show the single alert message for mysql multiple queries?
Just store the msg pieces in some variable, and alert them all finally.
$msgs = array ();
if ($query) {
$msgs [] = '.....';
} else {
$msgs [] = '...';
}
if ($meal_query) {
$msgs [] = '....';
} else {
$msgs [] = '...';
}
//....
if ($msgs) {
//join the msgs with line break
$alert = join ( "\n", $msgs );
//json encode will make sure it's like "..string..", no quotes problem
echo '<script> alert(', json_encode ( $alert ), '); </script>';
}
I have a javascript dropdown on website, here is the code-
<?php
function get_request_uri_without_page() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
$request = explode('/page/',$pageURL);
$request = explode('?', $request[0]);
return $request[0];
}
?>
<form action="<?php echo get_request_uri_without_page(); ?>" method="get" id="catselect" class="form-archive-140">
<!-- DROP DOWN HERE -->
<?php global $jtCatId; $jtCatId = true; wp_dropdown_categories('show_count=1&hierarchical=1&child_of=140&class=selectmenu&id=cat&show_option_none=Please Choose...'); ?>
<script type="text/javascript">
<!--
var dropdown = document.getElementById("cat");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
location.href = "<?php echo get_request_uri_without_page(); ?>?cat="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;
-->
</script>
The output of this dropdown is a list of posts filtered by location, however the URL structure is as follows-
thewebsite/themaincategory?cat=141
I would like to replace the category id at the end with the category name, when I replace dropdown.selectedIndex to "text" the dropdown does not work, it doesn't give an error it just doesn't do anything.
Do I need to do a rewrite in the htaccess or is their a way to get the above code working.
I would like to apologise in advance if this is a stupid question, I am new to javascript and just trying to find my way.
Here is a working example of the above mentioned-
http://www.theweddingdirectory.co.za/professional-wedding-photographers
try something like this
var cat= document.getElementById("cat");
var text = cat.options[cat.selectedIndex].text;
EDITED CODE
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
location.href = "<?php echo get_request_uri_without_page(); ?>?cat="+dropdown.options[dropdown.selectedIndex].text.trim();
}
}
I am using OO php and have the front end page generated through this class, I am trying to reload a button so that once it is pressed it changes class and button all together. Below is the function in which generates the buttons:
public static function printStartStopAll($enabled = 'false')
{
syslog(LOG_INFO, "HELLO");
?>
<div class="big-button-wrapper">
<?
if ( is_combined_server() ) {
// print start all button
$title_text = dgettext('triplecast', "Start All Transfers");
$btn_text = dgettext('triplecast', "Start All");
if ( !Transfer::CanTransferNow() || count(self::getPendingTransfers()) == 0 ) {
$class = "big-green-button-off";
$onclick='';
} else {
$class = "big-green-button";
$onclick = 'onclick=\'startAllTransfers("'.str_replace('"', '\"', self::$txtOpts).'");\'';
}
?>
<div id='start-all' class='<?=$class?>' title='<?=$title_text?>' <?=$onclick?>><?=$btn_text?></div>
<?
}
//Separate out the text for readability.
$title_text = dgettext('triplecast', "Stop Transfers and disable the system till you re-enable it in the configuration menu");
$btn_text = dgettext('triplecast', "Stop All");
$confirm_msg= dgettext('triplecast', 'If you continue all current transfers will be stopped and the system disabled till you re-enable it.');
$confirm = dgettext('triplecast', 'Do you want to stop all transfers?');
?>
<div id='stop-all' class='big-red-button' title='<?=$title_text?>' onclick='stopAllTransfers("<?=$confirm_msg.'\n\n'.$confirm?>", "<?=str_replace('"', '\"', self::$txtOpts)?>");'><?=$btn_text?></div>
<?
syslog(LOG_INFO, "===>".$enabled);
if($enabled != "true") {
$title_text = dgettext('triplecast', "Enable Select");
$btn_text = dgettext('triplecast', "Select");
$class = "big-green-button";
$onclick='onclick=\'enableSelect(true);\'';
?>
<div id='enable_select' class='<?=$class?>' title='<?=$title_text?>' <?=$onclick?>><?=$btn_text?></div>
<?
}
else {
$title_text = dgettext('triplecast', "Stop selected Transfers");
$btn_text = dgettext('triplecast', "Stop Selected");
?>
<div id='stop-select' class='big-red-button' title='<?=$title_text?>' onclick=''><?=$btn_text?></div>
<?
}
?>
</div>
<?
}
Please ignore any syslog :) thats me testing ...
I use ajax to push a variable back to the page and reload this function.
function enableSelect(value)
{
$.getJSON("ajax_requests/enableSelect.php", { enabled: value },
function(data){
});
}
<?php
$requireAuthentication = false;
$requireLicensing = false;
$minimalIncludes = true;
require_once('../Library.php');
header('content-type: application/json');
$enabled = getParameter('enabled');
$dist_server = TriplecastConfig::get('distribution_server');
$resp = new TriplecastMsg();
try {
TransferController::setSelectEnabled($enabled);
TransferController::printStartStopAll($enabled);
} catch (Exception $e) {
$resp->setCode(STATUS_ERROR);
$resp->setMessage($e->getMessage());
}
$json = new JSON();
echo $json->encode( array("code" => $resp->getCode(), "message" => $resp->getMessage())
);
?>
I understand that the code is messy, im just trying to figure out how to do this properly.
The aim of this is to enable the user to press this button and for it to reload the button with the stop-selected class (big-red-button)
Any help will be gratefully appreciated