I have the following view named 'findreseller.php':
<?php
$countries = CHtml::listData(Country::model()->findAll(), 'id', 'name');
echo CHtml::dropdownlist('find_reseller', '', $countries,
array('ajax'=>array(
'type'=>'POST',
'url'=>Yii::app()->getController()->createAbsoluteUrl('/webcare/reseller/loadAjaxData'),
'update' =>'#data',
)
)
);
?>
<div id="data">
<?php $this->renderPartial('_ajaxContent', array('dataProvider'=>$dataProvider))?>
</div>
_ajaxContent just echoes the result, nothing special there...
The dropdown, as you can see is generated with CHtml because I dont't need a form. I just need an onChange event to do something...
As per the code that follows, in '/webcare/reseller/loadAjaxData' I have:
public function actionLoadAjaxData() {
$country = $_POST['find_reseller'];
//do something...
$dataProvider=new CArrayDataProvider($country_reseller);
$this->render('findreseller', array('dataProvider' => $dataProvider));
}
I can tell that I am missing something, but I am not sure what exactly.
Edit
Modified like this:
<?php
//CHtml::form();
$countries = CHtml::listData(Country::model()->findAll(), 'id', 'name');
echo CHtml::dropdownlist('find_reseller', '', $countries,
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('/webcare/reseller/loadAjaxData'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city_id', //selector to update
'data'=>'js: $(this).val()',
//leave out the data key to pass all form values through
)
)
);
//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city_id','', array());
//CHtml::endForm();
?>
<div id="data">
<?php $this->renderPartial('_ajaxContent', array('dataProvider'=>$dataProvider))?>
</div>
And now I get:
http://prntscr.com/42wwx6
And I have the following controller action:
public function actionLoadAjaxData() {
$country = $_POST['country_id'];
...
$dataProvider=new CArrayDataProvider($country_reseller);
$data = User::model()->findAll('country_id=:country_id AND reseller=:reseller',
array(':country_id'=>(int) $_POST['country_id'], ':reseller'=>1));
$data=CHtml::listData($data,'city','city');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
$this->render('action_name', array('dataProvider' => $dataProvider));
}
Edit 2
If I write a die in actionLoadAjaxData(), right at the beginning, the method is loaded fine, the action is ok and the server answers 200.
Related
hello im so confused with my problem
the problem is the ajax didnt update the value
screenshot
while i choose kegiatan ajax didnt react/update.
idk were the error
please help me
this my controler code
public function actionDynamiclocation()
{
$data=Kegiatan::model()->findAll('nid=:nid',
array(':nid'=>(int) $_POST['nid']));
$data=CHtml::listData($data,'nid','lokasi','pengajuan','realisasi');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}
public function actionAjaxCreate() {$model=new Reportbean;
$outlets = Kegiatan::model()->findAll('nid=:nid',
array(':nid'=>(int) $_POST['nid']));
$model->lokasi=0;
$model->pengajuan=1;
$model->realisasi=2;
$this->renderPartial('_keg ', array('model'=>$model),false,true);
}
and view code
<div class="row">
<?php echo $form->labelEx($model,'kegiatan'); ?>
<?php echo $form->DropDownList($model,'kegiatan',
array(),
array(
'empty'=>'--pilih--',
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('Reportbean/ajaxCreate'), //url to call.
'data'=>array('nid'=>'js:this.value'),
'update'=>'.outlet',
//'update'=>'#'.CHtml::activeId($model,'lokasi'), //selector to update
//'data'=>array('nid'=>'js:this.value'),
))); ?>
<div class="outlet">
<?php
$this->renderPartial('_keg', array('model'=>$model),false,true);
?>
</div>
<?php
$this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'id'=>'keg',
'attributes'=>array(
'lokasi',
'pengajuan',
'realisasi',
),
));
?>
I am new to yii. I have a dependent dropdown, my problem is that in dependent dropdown when someone is editing, while editing the dropdown is not automatically selected.
Here is my form code:
<div class="row">
<?php
Yii::app()->clientScript->registerScript('courseDropdown','jQuery(function($) {
$("#Subject_Subjectid").trigger("change");
$("#Subjectcourse_CourseId").val(\''.$model->CourseId.'\');
});
');//write this code on _form.php file
?>
<?php echo $form->labelEx($model,'Subjectid'); ?>
<?php
$sub = CHtml::listData(Subject::model()->findAll(array("condition"=>"School_Id='$School' and Status=1")),'Subjectid','SubjectName');
echo CHtml::activeDropDownList($model,'Subjectid',CHtml::listData(Subject::model()->findAll(array("condition"=>"School_Id='$School' and Status=1")),'Subjectid','SubjectName'),
array(
'empty'=>'--Select a Subject--',
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('Timetable/subjectid'), //url to call.
'data'=>array('Subjectid'=>'js: $(this).val()'),
'update'=>'#CourseId', //selector to update
)));
echo $form->error($model,'Subjectid');
echo $form->labelEx($model,'CourseId');
echo CHtml::dropDownList('CourseId','', array(), array('empty' => '-- Select a Course --'));
echo $form->error($model,'CourseId');
?>
</div>
This is my controller action
public function actionSubjectid()
{
$SchoolId=Yii::app()->session['Schoolid'];
$subjectid=$_POST['Subjectid'];
$subject = Subject::model()->findByPk($subjectid);
$data = Subjectcourse::model()->findAll(array("order"=>"CourseName ASC", "select"=>"CourseId,CourseName","condition" => "SubjectId='$subjectid' AND Status=1 AND School_Id='$SchoolId'"));
$data=array('empty'=>'-- Select a Course --') +CHtml::listData($data,'CourseId','CourseName');
foreach($data as $value=>$name)
{
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true);
}
}
This is my action update
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Timetable']))
{
$model->attributes=$_POST['Timetable'];
$model->School_Id=Yii::app()->session['Schoolid'];
$CourseId=$_POST['CourseId'];
if($CourseId=="empty")
$model->CourseId='';
else
$model->CourseId=$_POST['CourseId'];
$model->Status=1;
if($model->save())
$this->redirect(array('view','id'=>$model->Id));
}
$this->render('update',array(
'model'=>$model,
));
}
As your second drop down will only work when a change event occurs in your first drop down, you can trigger this event when the page loads, something like this:
<?php
Yii::app()->clientScript->registerScript('courseDropdown','jQuery(function($) {
$("#Subject_Subjectid").trigger("change");
$("#Subjectcourse_CourseId").val(\''.$model->CourseId.'\');
});
');//write this code on _form.php file
?>
Edit: Alternatively, you could populate the second dropdown by querying data from the value of first dropdown:
if(!$model->isNewRecord) {
$courseArr = Chtml::listData(Subjectcourse::model()->findAllByAttributes(array('SubjectId'=>$model->Subjectid)), 'CourseId','CourseName'); //your query, modify according to need
} else {
$courseArr = array();
}
echo $form->labelEx($model,'CourseId');
echo CHtml::dropDownList('CourseId','', $courseArr, array('empty' => '-- Select a Course --'));
echo $form->error($model,'CourseId');
[SOLVED :: Updated the CODE ] There is a drop down list and a text filed. Text filed will be filled per drop down selection by Ajax in Yii form. And I need to pass parameter to controller via Ajax URL. It is working when I pass static parameter via URL. But failed to get the dynamic parameter.
My Form::
<div class="row">
<?php echo $form->labelEx($model,'pp_store'); ?>
<?php // echo $form->dropDownlist($model,'pp_store', CHtml::listData(Branchmaster::model()->findAll(), 'cm_branch', 'cm_branch')); ?>
<?php $storeArray = CHtml::listData(Branchmaster::model()->findAll(),'cm_branch','cm_branch');
echo $form->dropDownList($model,'pp_store', $storeArray,
array(
'empty'=>"Select Warehouse",
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('purchaseordhd/GetCurrency' ),
'update' => '#currencyid',
'data'=>array('store'=>'js:this.value',),
'success'=> 'function(data) {$("#currencyid").empty();
$("#currencyid").val(data);
} ',
),
)); ?>
<?php echo $form->error($model,'pp_store'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'pp_currency'); ?>
<?php echo $form->textField($model,'pp_currency', array('id'=>'currencyid', 'readonly'=> true)); ?>
<?php echo $form->error($model,'pp_currency'); ?>
</div>
My Controller::
public function actionGetCurrency()
{
$q = $_POST['store'];
$sql = "SELECT cm_currency as value FROM cm_branchmaster WHERE cm_branch= '$q' ";
$command = Yii::app()->db->createCommand($sql);
$result= $command->queryScalar();
echo $result;
}
When I send parameter from Ajax URl "array('pp_store'=>'333')" then it is working well. But I need to send data dynamically.
[SOLVED :: Updated the CODE ] Enjoy Coding
You don't want to pass the parameter as per below example. Current element value will be taken as parameter to controller through POST.
http://www.yiiframework.com/wiki/24/creating-a-dependent-dropdown/
echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('currentController/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city_id', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
)));
//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city_id','', array());
If you want to send data manually, then you have to uncomment the 'data'=>'js:javascript statement'.
About CActiveForm in document is:(clientOptions section)
ajaxVar: string, the name of the parameter indicating the request is an AJAX request. When the AJAX validation is triggered, a parameter named as this property will be sent together with the other form data to the server. The parameter value is the form ID. The server side can then detect who triggers the AJAX validation and react accordingly. Defaults to 'ajax'.
Now take a look in my example:
Summary: i have a form with two fields mail and newEmail, i submitted form via ajaxSubmitButton(if you need form code tell me put it). In following i get var_dump($_POST) content in two state:
First: Following var_dump($_POST) is for when a field(newEmail) is left empty:
array
'User' =>
array
'email' => string 'user#gmail.com' (length=14)
'newEmail' => string '' (length=0)
Second: Following var_dump($_POST) is for when all the fields are filled:
array
'User' =>
array
'email' => string 'user#gmail.com' (length=14)
'newEmail' => string 'admin#gmail.net' (length=19)
'ajax' => string 'email-form' (length=10)
'yt0' => string 'update' (length=18)
As you see only when all fields are filled the ajaxVar(ajax) exist in $_POST. When ajaxVar(ajax) initialized in CActiveForm?
Edit
email-form:
<?php
<div class="form">
<?php $form = $this->beginWidget('CActiveForm',array(
'id'=>'email-form',
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'focus'=>'input[type="email"]:first',
)
)); ?>
<div class="row">
<?php echo $form->label($model,'email') ?>
<?php echo $form->textField($model,'email') ?>
<?php echo $form->error($model,'email') ?>
</div>
<div class="row">
<?php echo $form->label($model,'newEmail') ?>
<?php echo $form->textField($model,'newEmail') ?>
<?php echo $form->error($model,'newEmail') ?>
</div>
<hr>
<div class="row">
<?php echo CHtml::ajaxSubmitButton(
'update',
Yii::app()->createUrl('upanel/user/CEmail'),
array(
'dataType'=>'json',
'type' => 'POST',
'data' => "js:$('#email-form').serialize()",
'success'=>'function(data){
if(data.status=="success")
{
//alert(data.status);
hideFormErrors(form="#email-form");
callback(status=data.status);
}else{
formErrors(data,form="#email-form");
}
}',
'beforeSend'=>'before',
),
array(
'id' => 'update-button'.uniqid(),
'class'=>'submit-button'
)
);
?>
</div>
<?php $this->endWidget() ?>
</div>
<?php echo $form->errorSummary($model,'please solve following errors:') ?>
actionCEmail:
public function actionCEmail()
{
/*ob_start();
var_dump($_POST);
$log=ob_get_contents();
$fp = fopen('data.html', 'w');
fwrite($fp, $log);
fclose($fp);
Yii::app()->end();*/ //This block active whenever i want see the $_POST content
$model = $this->loadModel(Yii::app()->user->id);
$model->scenario = 'CEmail';
$this->performAjaxValidation($model,'email-form');
if(Yii::app()->request->isAjaxRequest)
$this->renderPartial('_cemail',array('model'=>$model),false,true);
else
$this->render('update',array('model'=>$model,'form'=>'_cemail'));
}
protected function performAjaxValidation($model,$form)
{
if(isset($_POST['ajax']) && $_POST['ajax']===$form)
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
ajaxVar
initialized onsubmit if 'validateOnSubmit'=>true,. Try to use validateOnChange=>true and show your cactiveform code when init it.
And really stop invent "a bycicle".
Try to read http://learnyii.blogspot.com/2010/12/yii.html if you didnt understand my code in previous question.
I showed you working code of ajax validation which i use on working project. And with that method your $_POST will update on change of all fields with JSON object wich will contain errors for form.
Stop flooding community. Regards.
In your action:
public function actionCEmail()
{
$model = $this->loadModel(Yii::app()->user->id);
$model->scenario = 'CEmail';
if(Yii::app()->request->isAjaxRequest)
{
$error = CActiveForm::validate($model);
if($error!='[]')
{
echo $error;
Yii::app()->end();
}
}
if(isset($_POST['CEmailForm']))
{
//put form name in POST above
//do whatever you need with model here
//save / edit etc.
//in the end
echo CJSON::encode(array(
'status'=>'success',
));
Yii::app()->end();
}
if(Yii::app()->request->isAjaxRequest) //check renders
$this->renderPartial('_cemail',array('model'=>$model),false,true);
else
$this->render('update',array('model'=>$model,'form'=>'_cemail'));
}
In your view submit button:
<?php echo CHtml::ajaxSubmitButton ("Save", Yii::app()->request->url, array (
'dataType' => 'json',
'type'=>'post',
'success' =>
'js:function (data) {
if(data.status=="success"){
//do whatever you need on success
//show flash/notification
};
}
else {//show errors here
$.each(data, function(key, val) {
$("#YourFormIDhere #"+key+"_em_").text(val);
$("#YourFormIDhere #"+key+"_em_").css(\'display\',\'block\');
});
//can show error summarry here or custom notifications
};
}',
), array (
'id' => 'yourbuttonid_submit_'.rand(1,255), // Need a unique id or they start to conflict with more than one load.
));?>
Try to do like this. It works. Keep it simple. You lost 2? days to validation of 2 fields.
I just made this on my changepassword form. It took me 5 minutes.
My post when trying to save with default empty field:
{"UserChangePassword_verifyPassword":["Required field","Retype Password is incorrect."]}
Make like this and dont loose time. Regards.
I need to understand how to build Ajax request in Yii. I searched on the Yii website and found the following article :
http://www.yiiframework.com/wiki/24/
I wrote the code and I tested it on my localhost ? but for some reason it did not work.
For a first attempt I only wanted to do something simple. I wanted to print the result of another action on my page by using Ajax. The text that I want to be displayed is 'Hi'.
This is how mu code looks like for that action:
view/index
<?php
/* #var $this CurrentController */
$this->breadcrumbs=array(
'Current'=>array('/current'),
'index',
);
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-index-form',
'enableAjaxValidation'=>true,
)); ?>
<?php
echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('currentController/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city_id', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
)));
//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city_id','', array());
?>
<?php $this->endWidget(); ?>
</div><!-- form -->
Controller
<?php
class CurrentController extends Controller
{
public function accessRules()
{
return array(
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update','dynamiccities'),
'users'=>array('#'),
),
);
}
public $country_id;
public function actionIndex()
{
$this->render('index');
}
public function actionDynamiccities() /// Called Ajax
{
echo CHtml::tag('option',
array('value'=>'2'),CHtml::encode('Text'),true);
}
}
Unfortunately I'm not getting the desired result. What I get is:
drowpdown list contains country array.
another drowpdown list but empty ?!
How should I fix my example code so it would work? Can anyone see what I am doing wrong?
echo CHtml::dropDownList('city_id','', array());
use id as
echo CHtml::dropDownList('city_id','', array('id'=>'city_id'));