i am trying this sample about Creating a dependent dropdown i created form in provinceCity/_form and copy actionDynamiccities to ProvinceCityController.php but when i change dropDown list i have not any change ?
i think i must to enable ajax but i do not how i do it?
<?php echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('ProvinceController/dynamiccities'), //url to call.
//Style: CController::createUrl('ProvinceCity/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()); ?>
Here is what you will do in _form
<?php echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('ProvinceController/dynamiccities'), //url to call.
'update'=>'#city_name', //selector to update
'data'=>array('country_id' => 'js:this.value'),
)));
?>
</div>
<div id=city_name>
<?php echo $form->dropDownList($model, 'city_id', array()); ?>
</div>
Hopefully, it would help you.
It should be,
<?php
$countryAry=array(1=>'USA',2=>'France',3=>'Japan');
echo CHtml::dropDownList('country_id','', $countryAry,
array
(
'ajax' => array
(
'type'=>'POST',
'url'=>CController::createUrl('Controller/action'),
'dataType'=>'JSON',
'success'=>'js:function(data)'
. '{'
. ' var opt="<option value=>-----Select city-----</option>";'
. ' $.each(data,function(i,obj)'
. ' {'
. ' opt+="<option value=\'"+obj.id+"\'>"+obj.name+"</option>";'
. ' });'
. ' $("#city_id").html(opt);'
. '}'
)
));
echo CHtml::dropDownList('city_id','', array());
?>
But, I suggest you to implement this task as showing bellow.
<?php
$countryAry=array(1=>'USA',2=>'France',3=>'Japan');
echo CHtml::dropDownList('country_id','', $countryAry,array('onchange'=>'js:getCities()'));
echo CHtml::dropDownList('city_id','', array());
?>
<script type="text/javascript">
function getCities()
{
$.ajax
({
type:'POST',
url:'Controller/action',
dataType:'JSON',
success:function(data)
{
var opt="<option value=>-----Select city-----</option>";
$.each(data,function(i,obj)
{
opt+="<option value='"+obj.id+"'>"+obj.name+"</option>";
});
$("#city_id").html(opt);
}
});
}
</script>
I found the solution here Dependent dropdown list in yii
<?php
$model=new ModelClass; // initilize it in controller
$form=$this->beginWidget('CActiveForm', array(
'id'=>'dependent-form',
'enableClientValidation'=>true,
'htmlOptions' => array('enctype' => 'multipart/form-data','autocomplete'=>'off'),
'clientOptions'=>array(
'validateOnSubmit'=>true,
)
));
?>
<div class="row">
<?php
echo $form->dropDownList($model,'country_id',
CHtml::listData(Countries::model()->findAll(), 'id', 'title'),
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>Yii::app()->createUrl('YourController/loadstates'), // get states list
'update'=>'#ModelClass_state_id', // add the state dropdown id
'data'=>array('country_id'=>'js:this.value'),
)));
?>
</div>
<div class="row">
<?php
echo $form->dropDownList($model,'state_id',
array(),
array(
'prompt'=>'Select State',
'ajax' => array(
'type'=>'POST',
'url'=>Yii::app()->createUrl('YourController/loadcities'), // get states list
'update'=>'#ModelClass_city_id', // add the state dropdown id
'data'=>array('state_id'=>'js:this.value'),
)));
?>
</div>
<div class="row">
<?php
echo $form->dropDownList($model,'city_id',array(),array('empty'=>'-choose city-'));
?>
</div>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Add' : 'Update',array('class'=>'btn btn-primary')); ?>
<?php $this->endWidget(); ?>
Related
Hello I have dropdownlist dependant textfield. The value of the textfield should be updated via ajax request when dropdownlist is selected (I'm using Yii's CHTML textfield).
Here is my code :
view _form.php
<div class="row">
<?php echo $form->labelEx($model,'kode_rincian'); ?>
<?php
echo $form->dropDownList($model, 'kode_rincian', array(), array(
'empty'=>'--Pilih--',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('OPS/calculateRealisasi'),
//'update'=>'#OPS_contrealisasi',
'dataType'=>'json',
'data'=>array(
'kode_program' => 'js:$(\'#OPS_kode_program option:selected\').val()',
'kode_kegiatan' => 'js:$(\'#OPS_kode_kegiatan option:selected\').val()',
'kode_output' => 'js:$(\'#OPS_kode_output option:selected\').val()',
'kode_komponen' => 'js:$(\'#OPS_kode_komponen option:selected\').val()',
'kode_akun' => 'js:$(\'#OPS_kode_akun option:selected\').val()',
'kode_rincian'=>'js:this.value',
),
'success'=>"function(data)
{
$('#OPS_realisasi_at').html(data.sumrealisasi);
$('#OPS_sisa_at').html(data.sumsisa);
} ",
)
));
?>
<?php echo $form->error($model,'kode_rincian'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'realisasi_at'); ?>
<?php
echo $form->textField($model,'realisasi_at');
?>
<?php echo $form->error($model,'realisasi_at'); ?>
</div class="row">
<?php echo $form->labelEx($model,'sisa_at'); ?>
<?php echo $form->textField($model,'sisa_at'); ?>
<?php echo $form->error($model,'sisa_at'); ?>
</div>
And controller OPSController.php:
public function actionCalculateRealisasi(){
$kode_rincian = $_POST["kode_rincian"];
$kode_program = $_POST["kode_program"];
$kode_kegiatan = $_POST["kode_kegiatan"];
$kode_komponen = $_POST["kode_komponen"];
$kode_akun = $_POST["kode_akun"];
$kode_output = $_POST["kode_output"];
$modelkode= KodePOK::model()->findByAttributes(array(
'kode_program'=>$kode_program,
'kode_komponen'=>$kode_komponen,
'kode_kegiatan'=>$kode_kegiatan,
'kode_akun'=>$kode_akun,
'kode_output'=>$kode_output,
'kode_rincian'=>$kode_rincian,
));
if($modelkode!=NULL){
$idpok=$modelkode->id_pok;
}
else{
$idpok=0;
}
$criteria = new CDbCriteria;
$criteria->select='SUM(jumlah_pengajuan) as realisasi';
$criteria->condition="id_pok='".$idpok."'";
$sum = OPS::model()->find($criteria);
$sumrealisasi=$sum->realisasi;
$sumrealisasi=(int)$sumrealisasi;
$calcsisa=POK::model()->findByPk($idpok);
$getjumlah=$calcsisa->jumlah_pagu;
$sumsisa=$getjumlah-$sumrealisasi;
echo CJSON::encode(array(
'sumrealisasi'=>$sumrealisasi,
'sumsisa'=>$sumsisa,
));
Yii::app()->end();
}
The code didn't show any error but the textfield wasn't updated. Please help me. Here is the result when I tried to inspect the page element :
I've solved the problem.
I changed
'success'=>"function(data)
{ $('#OPS_realisasi_at').html(data.sumrealisasi);
$('#OPS_sisa_at').html(data.sumsisa);
} ",
to :
'success'=>"function(data)
{ $('#OPS_realisasi_at').val(data.sumrealisasi);
$('#OPS_sisa_at').val(data.sumsisa);
} ",
On Post requests <?php echo $form->errorSummary($model) ?> automatically appears on the page after submitting form and show summary of form errors. How can make it appear on Ajax requests?
Edit:
Following is my view file:
<div class="form" >
<?php
$form = $this->beginWidget('CActiveForm',array(
'id'=>'change-profile-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'action' => Yii::app()->createUrl('upanel/user/CProfile'),
'method' => 'POST',
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>true,
'validateOnType'=>false,
),
));
?>
.
.
.
<div class="row">
<?php
echo CHtml::ajaxSubmitButton(
'update',
Yii::app()->createUrl('upanel/user/CProfile'),
array(
'type'=>'POST',
'data'=>"js:$('#change-profile-form').serialize()",
'success'=>'callback',
'beforeSend'=>'before',
),
array(
'id'=>'update-button'.uniqid(),
'class'=>'submit-button',
)
);
?>
</div>
<?php $this->endWidget() ?>
</div> <!-- End The Profile Form -->
<?php echo $form->errorSummary($model,'Please solve these errors:') ?>
clientOptions can also accept:
'afterValidate' => 'js:function(form, data, hasError){
if(hasError){
// do something with: data
}
}'
What i do is something like this http://phpfiddle.org/lite/code/4j3-6rx then on the server side, i just return a json message that gets parsed on the ajax success callback, pretty simple.
I have a CActiveForm which when submitted should make a second CActiveForm become visible. I know how to change the htmlOptions of the form when its created but not how to access it via the controller.
My View with two forms. The second form has visibility:hidden
<div class="form">
<?php
$numberForm = $this->beginWidget('CActiveForm', array(
'id' => 'addnumber-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
<p class="note"><?php echo UserModule::t('Fields with <span class="required">*</span> are required.'); ?></p>
<?php echo $numberForm->errorSummary($numberModel); ?>
<div class="row">
<?php echo $numberForm->labelEx($numberModel, 'number'); ?>
<?php echo $numberForm->textField($numberModel, 'number'); ?>
<?php echo $numberForm->error($numberModel, 'number'); ?>
<?php
echo CHtml::submitButton(UserModule::t("Verify"), array(
"class" => "btn btn-success"
));
?>
</div>
<?php $this->endWidget(); ?>
<?php
$verifyForm = $this->beginWidget('CActiveForm', array(
'id' => 'verify-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'htmlOptions' => array("style"=>"visibility: hidden"),
));
?>
<?php echo $verifyForm->errorSummary($verifyModel); ?>
<p>A authorisation code has been sent to your phone. Please enter it below. If you don't receive a text message make sure you entered your number correctly and try again</p>
<div class="row">
<?php echo $verifyForm->labelEx($verifyModel, 'authcodeUser'); ?>
<?php echo $verifyForm->textField($verifyModel, 'authcodeUser'); ?>
<?php echo $verifyForm->error($verifyModel, 'authcodeUser'); ?>
<?php
echo CHtml::submitButton(UserModule::t("Confirm"), array(
"class" => "btn btn-success"
));
?>
<?php
foreach(Yii::app()->user->getFlashes() as $key => $message) {
echo '<div class="flash-' . $key . '">' . $message . "</div>\n";
}
?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
My controller for these forms
public function actionAddnumber(){
$numberModel = new UserAddNumber;
$verifyModel = new UserVerifyNumber;
if (Yii::app()->user->id) {
// ajax validator
if(isset($_POST['ajax']) && $_POST['ajax']==='addnumber-form')
{
echo UActiveForm::validate($numberModel);
Yii::app()->end();
}
if(isset($_POST['UserAddNumber'])) {
$numberModel->attributes=$_POST['UserAddNumber'];
if($numberModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNo = $numberModel->number;
$profile->save();
//MAKE $verifyForm visibility to visible uring htmlOptions
Yii::app()->session['authcode'] = '4444';
}
}
if(isset($_POST['UserVerifyNumber'])) {
$verifyModel->attributes=$_POST['UserVerifyNumber'];
if($verifyModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNoVerified = True;
$profile->save();
Yii::app()->user->setFlash('profileMessage',UserModule::t("Your mobile number has been verified"));
$this->redirect(array("profile"));
}
}
}
$this->render('addnumber', array('numberModel'=>$numberModel, 'verifyModel' => $verifyModel));
}
It looks like you could just create a new variable for whether or not to show the second form and then pass it to the view. Here is your controller:
public function actionAddnumber(){
$numberModel = new UserAddNumber;
$verifyModel = new UserVerifyNumber;
$formVisibility = "hidden";
if (Yii::app()->user->id) {
// ajax validator
if(isset($_POST['ajax']) && $_POST['ajax']==='addnumber-form')
{
echo UActiveForm::validate($numberModel);
Yii::app()->end();
}
if(isset($_POST['UserAddNumber'])) {
$numberModel->attributes=$_POST['UserAddNumber'];
if($numberModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNo = $numberModel->number;
$profile->save();
//MAKE $verifyForm visibility to visible uring htmlOptions
$formVisibility = "visible";
Yii::app()->session['authcode'] = '4444';
}
}
if(isset($_POST['UserVerifyNumber'])) {
$verifyModel->attributes=$_POST['UserVerifyNumber'];
if($verifyModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNoVerified = True;
$profile->save();
Yii::app()->user->setFlash('profileMessage',UserModule::t("Your mobile number has been verified"));
$this->redirect(array("profile"));
}
}
}
$this->render('addnumber', array('numberModel'=>$numberModel, 'verifyModel' => $verifyModel, 'formVisibility' => $formVisibility));
}
And here is the first part of your second form:
<?php
$verifyForm = $this->beginWidget('CActiveForm', array(
'id' => 'verify-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'htmlOptions' => array("style"=>"visibility: ".$formVisibility),
));
?>
[edit] To make sure I am answering your question, I should add that I've never seen any way of changing the htmlOptions from the controller directly. That's why I proposed this solution instead.
I have Yii form. Some fields are required. When form is submitted i need that CSS class "error" would be added to the text input. My Code:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<ul class="contact_form">
<li class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name', array('class'=>'input')); ?>
<?php echo $form->error($model,'name'); ?>
</li>
...
Now i just get div with error message:
<div class="errorMessage" id="ContactForm_name_em_" style="">Laukelis „Vardas, pavardė“ negali būti tuščias.</div>
How to add "error" class to input field?
<?php echo $form->textField($model,'name', array('class'=>'input' . ( $model->getError('name') ? ' error' : ''))); ?>
To have AJAX validation also, you should add something more or less like this:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'afterValidate' => 'js:function(form, data, hasError) {
if(hasError) {
for(var i in data) $("#"+i).addClass("error_input");
return false;
}
else {
form.children().removeClass("error_input");
return true;
}
}',
'afterValidateAttribute' => 'js:function(form, attribute, data, hasError) {
if(hasError) $("#"+attribute.id).addClass("error_input");
else $("#"+attribute.id).removeClass("error_input");
}'
),
)); ?>
I am doing a yii web application
i have a drop down list that should be dependent on another , i use ajax however it doesnt work.
ive seen the yii tutorial for dependent drop downs and searched everywhere.
http://www.yiiframework.com/wiki/24
this is my main drop down list:
<div class="row">
<?php echo $form->labelEx($model, 'sourceID'); ?>
<?php
echo $form->dropDownList($model, 'sourceID', CHtml::listData(Sources::model()->findAll(), 'sourceID', 'name'), array('empty' => 'select source'), array(
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('reservations/atest'),
'update' => '#meal'
)
)
);
?>
<?php echo $form->error($model, 'sourceID'); ?>
</div>
this is the dependent drop down list :
<div class="row">
<?php echo $form->labelEx($model, 'meal'); ?>
<?php echo $form->dropDownList($model, 'meal', array()); ?>
<?php echo $form->error($model, 'meal'); ?>
</div>
this is my controller action:
public function actionAtest() {
$data = Sources::model()->findAll();
$data = CHtml::listData($data, 'sourceID', 'name');
foreach ($data as $value => $name) {
echo CHtml::tag('option', array('value' => $value), CHtml::encode($name),true);
} }
also, i added the action to the access rules.
any help is appreciated ,
thank you in advance.
You placed the ajax option after the htmlOptions. Here is the modified code
<div class="row">
<?php echo $form->labelEx($model, 'sourceID'); ?>
<?php
echo $form->dropDownList($model, 'sourceID', CHtml::listData(Sources::model()->findAll(), 'sourceID', 'name'), array('empty' => 'select source','ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('reservations/atest'),
'update' => '#meal'
)
)
);
?>
<?php echo $form->error($model, 'sourceID'); ?>
</div>
And instead of using forms dropdownlist use CHtml::dropDownList for the dependent drop-down.
echo CHtml::dropDownList('meal','', array());
You can also use CActiveForm::dropDownList but in that case you have to use CHtml::resolveNameId in the update option of ajax