Tushar Walzade Tushar Walzade - 3 months ago 182x
PHP Question

Yii2 : Dependent Dropdown List

I want to use dependent dropdown list in yii2-advanced app, using 2 models -

BusinessMainCategories(bmc_id, bmc_name) & BusinessSubCategories(bsc_id, bsc_name, bmc_id)
. I've to use the dropdown list on the page located in frontend.
I've tried the following but it displays all the sub categories in db every time.

My view code is as -

<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
$dataBMC = ArrayHelper::map(\backend\models\BusinessMainCategories::find()->asArray()->all(), 'bmc_id', 'bmc_name');
echo $form->field($model, 'bmc_id')->dropDownList($dataBMC,
['prompt'=>'Choose a Main Category',
function(data) {
$("select#business_sub_categories-bsc_id" ).html( data );
echo "<br>";
$dataBSC = ArrayHelper::map(\backend\models\BusinessSubCategories::find()->asArray()->all(), 'bsc_id', 'bsc_name');
echo $form->field($model, 'bmc_id')
['prompt'=>'Choose a Sub Category',
<div class="form-group"><br>
&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="Submit" class='btn btn-success'>
<?php ActiveForm::end(); ?>

I'm confused with where should I write the code for list function? I'm writing it in backend\controllers\BusinessSubCategoriesController as follows -

public function actionLists($id)
$countBSCategories = BusinessSubCategories::find()->where(['bmc_id' => $id])->count();
$businessSubCategories = BusinessSubCategories::find()->where(['bmc_id' => $id])->all();
if ($countBSCategories > 0) {
foreach ($businessSubCategories as $businessSubCategory) {
echo "<option value='" . $businessSubCategory->bsc_id . "'>" . $businessSubCategory->bsc_name . "</option>";
} else {
echo "<option> - </option>";

I think the function is not getting 'bmc_id' properly. Please tell me a solution to make it dependent by correcting my mistakes...


The Same Scenario-

<?= $form->field($model, 'category_id')->dropDownList(ArrayHelper::map(ItemCategory::find()->all(),'id','ic_code'),['prompt'=>'Select Category',
                    'onchange' => '
                    $.post("index.php?r=receiving-order-details/lists&id=' . '"+$(this).val(),function(data){
                    });']) ?>

<?= $form->field($model, 'sub_category_id')->dropDownList(ArrayHelper::map(ItemSubCategory::find()->all(),'id','isc_code'),['prompt'=>'Select Sub Category']) ?>