Jaya Kumari Jaya Kumari - 4 months ago 15
Javascript Question

How to create dependent dropdown in yii2

I use this code on

backend/views/_form.php


<?php $CoursesCat = ArrayHelper::map(CoursesCat::find()->all(),'id', 'cat_name');
$CoursesSubcat = ArrayHelper::map(CoursesSubcat::find()->all(),'id', 'name');
$form = ActiveForm::begin(); ?>

<?php
echo $form->field($model, 'cat_id')->dropDownList($CoursesCat,
['prompt'=>'-Choose a Category-',
'onchange'=>'
$.post( "'.urldecode(Yii::$app->urlManager->createUrl('coursedetail/lists&id=')).'"+$(this).val(), function( data ) {
$( "select#subcat_id" ).html( data );
});
']);


echo $form->field($model, 'subcat_id')
->dropDownList( $CoursesSubcat
['prompt'=>'-Choose a Sub Category-'],
['id'=>'subcat_id']
); ?>

Answer
public function actionLists($id)
{
   echo $sql = "select * from courses_subcat  where cat_id='$id' ";
    $models = CoursesSubcat::findBySql($sql)->asArray()->all();   
    //echo "<pre>";print_r($model);exit;

    if(sizeof($models) >0){
        echo "<option>-Choose a Sub Category-</option>";
        foreach($models as $model){
            echo "<option value='".$model['id']."'>".$model['name']."</option>";
        }
    }
    else{
        echo "<option>-Choose a Sub Category-</option><option></option>";
    }

}