Insert data into Dropdownlist by ajax request in yii

This turorial have the details of dynamic data insertion to dropdownlist using ajax. I added the source code below for this concept. We have two dropdownlist in form “usercategory”,”usertype”. When we change the usercategory, usercategory related usertype will show in “usertype” dropdownlist.

In view.php

<div class="row">
   <?php echo $form->labelEx($model,'usercategory'); ?>
   <?php $categories=Yii::app()->Datacomponent->usercategory();
   echo $form->dropdownlist($model,
                          'usercategory',
                          $categories,
                          array('empty'=>'Select Category ',
                            'ajax'=>array(
                                'type'=>'POST',
                                'url'=>CController::createUrl('default/usertype'),
                                'update'=>'#User_usertype',
                                'data'=>array('categoryid'=>'js:this.value'),
                             ),
                          )); 
  ?> 
  <?php echo $form->error($model,'usercategory'); ?>
</div>
    
<div class="row">
 <?php echo $form->labelEx($model,'usertype'); ?>
 <?php echo form->dropDownList($model,
                                 'usertype',
                                 array('empty'=>'Select Type')); 
?>
<?php echo $form->error($model,'usertype'); ?>
</div>

In controller.php

<php
class SiteController extends Controller {
    ...............
    ...............
    public function actionUsertype(){
     if(isset($_POST['categoryid']) && $_POST['categoryid']!=''){
            $categoryid=$_POST['categoryid'];
            $usertype=Usertype::model()->findAll(array(
                                        'select'=>'usertypeid,type',
                                        'condition'=>"usercategoryid='$categoryid'"
                                      ));       
                 
            $data=CHtml::listData($usertype,'usertypeid','type');
            echo CHtml::tag('option',array('value' => ''),
                               CHtml::encode('Select User Type'),true);
    
            foreach($data as $id => $value)
            {
              echo CHtml::tag('option',array('value'=>$id),CHtml::encode($value),true);
            }                
       }
     }
}
?<

Leave a Reply

Your email address will not be published. Required fields are marked *