Sometimes new Yii guys face problem to manage dependent dropDownList using AJAX. I am going to discuss an easy solution about this issue.
Example code:
Code in View-
echo CHtml::dropDownList('region_id','', array(2=>'New England',1=>'Middle Atlantic',3=>'East North Central'), array( 'prompt'=>'Select Region', 'ajax' => array( 'type'=>'POST', 'url'=>CController::createUrl('loadcities'), 'update'=>'#city_name', 'data'=>array('region_id'=>'js:this.value'), ))); echo CHtml::dropDownList('city_name','', array(), array('prompt'=>'Select City'));
Code in Controller-
public function actionLoadcities() { $data=RegionCity::model()->findAll('region_id=:region_id', array(':region_id'=>(int) $_POST['region_id'])); $data=CHtml::listData($data,'id','city_name'); echo "<option value=''>Select City</option>"; foreach($data as $value=>$city_name) echo CHtml::tag('option', array('value'=>$value),CHtml::encode($city_name),true); }
I think this will help to understand actually how AJAX works in Yii for dependent dropDownList also AJAX working behavior in Yii framework.
--Enjoy, Explore... Yii
Total 6 comments
Did you ever figure out what the problem was from Your own comment on the orginal topic / tip.. This is the same exact thing aka repost with no solution.
hi, this is the independant dropdown list case, is there an article for dropdownlist from model which get the parent and the child values from the parent?
i need a detailed example, i am new in using yii
thank you
i used the same coding as given above, im getting error undefined index : region_id, help needed
I've three drop down. 1. Provinces (Hard-codded values) 2. Districts (Filling the drop down using Ajax, working perfect) View Part for the Districts:
Any advice?
It is working fine for display part, I was able to get the first down values using $model but how to save dependent drop down value to $model?
nice tutorial
Leave a comment
Please login to leave your comment.