How to develop dependant drop down without database

489 views Asked by At

I have following code in my controller:

 public function getData($property)
    {
        $data = array(
             'type'=>array(
               'PC',
           'Laptop'
            ),
            'brand'=>array(
               '1'=>array( 
                   'ASUS PC',
                   'DELL PC',
            ),
            '2'=>array( 
                   'ASUS laptop',
                   'DELL laptop',
            ),

        );
        return $data[$property];
    }

In my view:

 <?=  $form->dropDownList($model, 'type',$model->getData('type'), array('class' => 'form-control')) ?>

This code(in the view) returns types.(e.g shows pc and laptop options in the drop down ).

I need to develop dependant drop that will show 'ASUS PC'and 'DELL PC' in the drop down, if user chooses pc option from the the first drop down(type). How can I do it.

1

There are 1 answers

0
Passionate Coder On

1) add two dropdown fields in view page.

<?php echo  $form->dropDownList($model, 'type',array('PC'=>'PC','Laptop'=>'Laptops'),
array(
  'empty'=>'--Select Product Type---' ,  
  'ajax' => array(
  'type'=>'POST', //request type
  'url'=>CController::createUrl('yourcontroller/getData'), //url to call.
  'data'=>array('type'=>'js:this.value'),// value to send
  'update'=>'#dependent_value', //selector to update

))); ?>

//empty since it will be filled by the other dropdown
<div class="row">
        <?php echo CHtml::dropDownList('dependent_value','', array()); ?>


    </div>

Controller

public function actionGetData() {
        $data = array('type' => array('PC', 'Laptop'), 'brand' => array('1' => array('ASUS PC', 'DELL PC'), '2' => array('ASUS laptop', 'DELL laptop')));
        //echo "<pre>";print_r($_POST['type']);die;
        if ($_POST['type'] == 'PC') {

            $arr = $data['brand'][1];
        } elseif ($_POST['type'] == 'Laptop') {

            $arr = $data['brand'][2];
        } else {
            $arr = array();
        }
        echo CHtml::tag('option', array('value' => $value), CHtml::encode("Select Product Brand--"), true);
        foreach ($arr as $value => $name) {
            echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
        }
    }

Note : Make sure to set permission to access this action in accessRules