Wednesday, May 16, 2012

Yii dropDownList onChange

    <div class="row">
        <?php echo $form->labelEx($model,'clientid'); ?>
        <?php //echo $form->textField($model,'projectid'); ?>
         <?php echo $form->dropDownList($model,'clientid', CHtml::listData(Client::model()->findAll(), 'code','name'),
                                array(
                        'prompt' => '--Please Select --',
                        'value' => '0',
                        'ajax'  => array(
                        'type'  => 'POST',
                        'url' => CController::createUrl('task/projects'),
                        'update' => '#Task_projectid',   //selector to update value
                        'data' => array('clientid'=>'js:this.value'),
                        )      
                        )
        ); ?>

 </div>


    <div class="row">
                <?php echo $form->labelEx($model,'projectid'); ?>
                <?php echo $form->dropDownList($model,'projectid', array('empty'=>'--please select--')); ?>
                <?php echo $form->error($model,'projectid'); ?>
        </div>

The controller action

 public function actionProjects()
        {
        $giatUnit = (!empty($_POST['clientid'])) ? $_POST['clientid']: '0';

                $data=Project::model()->findAll('clientid=:clientid',
                                array(':clientid'=>$giatUnit));


                $data=CHtml::listData($data,'id','name');
                foreach($data as $value=>$name)
                {
                echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
                }      


        }

7 comments:

  1. may i know please
    what we are giving in url...
    please reply soon...
    thanks in advance

    ReplyDelete
    Replies
    1. Because it is dependent dropdown.
      The first dropdown is filled with several value/name pairs of countries. Whenever it is changed an ajax request will be done to the 'task/projects' action of the current controller. The result of that request (output of the 'projects' action) will be placed in the second dropdown with id is #Task_projectid.

      Delete
  2. need your help, any idea to make two dropdownlist depend on one dropdownlist?

    ReplyDelete
  3. thank you very much. this's exactly what I need now

    ReplyDelete
  4. please help me...i have two table branc and unit, how to create dropdown form??

    ReplyDelete
    Replies
    1. Do you want two dropdownlist depend on one dropdownlist?

      Delete