How to create dependent dropdown in yii2

2020-08-01 06:51发布

问题:

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']
    ); ?>

回答1:

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>";
    }

}


回答2:

use the krajee extension for dependent drop down

Details is here Krejee dependent dropdown for yii2 http://demos.krajee.com/widget-details/depdrop

or follow following instructions:

Install the extension via composer:

 $ php composer.phar require kartik-v/dependent-dropdown "dev-master"

In your view :

  use kartik\widgets\DepDrop;

// Normal parent select

echo $form->field($model, 'cat')->dropDownList($catList, ['id' => 'cat-id']);

// Dependent Dropdown

echo $form->field($model, 'subcat')->widget(DepDrop::classname(), [
    'options' => ['id' => 'subcat-id'],
    'pluginOptions' => [
        'depends' => ['cat-id'],
        'placeholder' => 'Select...',
        'url' => Url::to(['/site/subcat'])
    ]
]);

// THE CONTROLLER

public function actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = self::getSubCatList($cat_id);
// the getSubCatList function will query the database based on the
// cat_id and return an array like below:
// [
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]
echo Json::encode(['output'=>$out, 'selected'=>'']);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}


标签: jquery yii2