How to make dependent dropdown using select2 widget yii

875 Views Asked by At

I want to make a dependent dropdown using select2, but i cannot change the data for the next dropdown($kabupaten), this is my code in view :

<?php $this->widget('ext.select2.ESelect2', array(
'model' => $model,
'attribute' => 'provinsi',
'data' => $provinsi,
'htmlOptions' => array(
    'style' => 'width:440px',
    'prompt' => '-- Pilih Provinsi --',
    'ajax' => array(
        'type' => 'POST',
        'url' => CController::createUrl('Kabupaten/SelectKabupaten'),
        'class' => 'span5',
        'update' => '#' . CHtml::activeId($model, 'kabupaten'), 
    )),));
$this->widget('ext.select2.ESelect2', array(
  'model' => $model,
  'attribute' => 'kabupaten',
  'data' => $kabupaten,
  'htmlOptions' => array(
    'style' => 'width:440px',
    'prompt' => '-- Pilih Kabupaten --',
),));?>

and this is my cotroller :

public function actionSelectKabupaten() {
    $id_kabupaten = $_POST['DataDiriAnak']['provinsi'];
    $kabupaten = CHtml::listData(Kabupaten::model()->findByAttributes(array('IDProvinsi'=>$id_kabupaten)), 'Nama', 'Nama');
}   

I dont know how to send value of $kabupaten to my last select2 dropdown

1

There are 1 best solutions below

1
On

You can send value of $kabupaten in your view by encoding data in CHtml::tag() as follows:

public function actionSelectKabupaten() {
    $id_kabupaten = $_POST['DataDiriAnak']['provinsi'];
    $kabupaten = CHtml::listData(Kabupaten::model()->findByAttributes(array('IDProvinsi'=>$id_kabupaten)), 'Nama', 'Nama');
        foreach($kabupaten as $value => $name) {
                echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
        }
} 

Let me know incase of any further query for the same.