user1947777
user1947777

Reputation: 87

How to create dependent dropdown box in yii

I am working in yii framework. i want to create dependent dropdown box. First dropdown box is having categories which i am fetching from database. i have code for category dropdown box as-

<div class="row">
<?php echo $form->labelEx($model,'category'); ?>
<?php echo $form->dropdownList($model,'category', CHtml::listData(Category::model()->findAll(), 'categoryId', 'category'), array('empty'=>'Choose one')); ?>
<?php echo $form->error($model,'category'); ?>
</div>

Now i want to create next dropdown box of items which will load items of only above selected category. i am having items as another table which is having categoryId as forein key. So how to get above selected categoryId to load its relative items on same view form?

Upvotes: 0

Views: 1654

Answers (1)

Add jquery into your view:

$('#choose-type').change(function() {
            var type = $(this).val();
                $.ajax({
                    type: "GET",
                    url: "<?php echo Yii::app()->request->baseUrl; ?>/your_path/chooseBrand",
                    data: "type="+type,
                    dataType: 'json',
                    success: function(data){
                        // decode data and add to your dropdown                            
                    },
                });   

        });

And in your controller:

public function actionChooseBrand() {
        $type       = (int)$_GET['type'];
        $brands     = Brands::model()->findAllByAttributes(array('type_id' => $type)); 
        $data       = array();

        foreach($brands as $brand) {
            $data[$brand->id] = $brand->name;
        }
        echo json_encode($data);
        exit;
    }

That how i do... :D

Upvotes: 1

Related Questions