Sample :
* City -> (Dependent ke) Province.
* Model yang digunakan City dan Province.

1. _FORM (../protected/views/city/_form.php)

echo $form->dropDownList($model, ‘regional_code’, CHtml::listData(Regional::model()->findAll(), ‘regional_code’, ‘regional_name’),

array( ‘prompt’=>’Select Regional’,

‘ajax’=>array(

‘type’=>’POST’,
‘url’=>CController::createUrl(‘City/changeprovince‘),
‘update’=>’#’.CHtml::activeId($model, ‘province_code‘), // province_code merupakan dropdown selanjutnya
‘data’=>array(‘regional_code’=>’js:this.value’), // regional_code, field yang dikirim (default semua field)

)

)

);

Note :
– City = Model City.
changeprovince = Function di Controller.
$model, berfungsi untuk automatic selected pada dropdown saat melakukan edit.
CHtml::listData(Regional::model()->findAll(), ‘regional_code’, ‘regional_name’) = Menampilkan semua data Model Regional.

 

2. BUAT FUNCTION “actionChangeprovince()di CONTROLLER (../protected/controllers/CityController.php)

public function actionChangeprovince()

{

$models = province::model()->findAll(‘regional_code=:regional_code’, array(‘:regional_code’=>$_POST[‘regional_code’]));
$data = CHtml::listData($models,’province_code’,’province_name’);

if ($data)
{

echo CHtml::tag(‘option’,array(‘value’=>” ),CHtml::encode(‘Select Province’),true);
foreach($data as $value=>$name)

{

echo CHtml::tag(‘option’,array(‘value’=>$value),CHtml::encode($name),true);

}

}

else

echo CHtml::tag(‘option’,array(‘value’=>”),CHtml::encode(‘- No Province -‘),true);

}

Note :
– Penamaan Function dengan menambahkan action dan nama function diawali Kapital. Misal “actionChangeprovince“.
$_POST[‘regional_code’], field dari model Regional.

 

3. TAMBAHKAN hak akses pada CONTROLLER (../protected/controllers/CityController.php)

array(‘allow’, // allow authenticated user to perform ‘create’ and ‘update’ actions

‘actions’=>array(‘create’,’update’,‘changeprovince’),
‘users’=>array(‘@’),

),

Note :
changeprovince, Function di Controller.

Sumber : Yii