An Easy Solution for Dependent dropDownList Using AJAX

You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#4) »

Sometimes new Yii guys face problem to manage dependent dropDownList using AJAX. I am going to discuss about an easy solution about this issue.

Example code:

Code in View-

<?php									
  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

7 1
24 followers
Viewed: 87 627 times
Version: Unknown (update)
Category: Tips
Written by: mrs
Last updated by: Kostas Apazidis (KonApaz)
Created on: Dec 9, 2012
Last updated: 4 years ago
Update Article

Revisions

View all history

Related Articles