dependent dropdown yii2. How to do?

前端 未结 4 1884
野的像风
野的像风 2020-12-05 21:58

can I create a dependent dropdown in yii2?

I have two tables:

\'id\',\'name_country\"
\'id\',\'name_city\',\'country_id\'

and have

4条回答
  •  攒了一身酷
    2020-12-05 22:53

    use the krajee extension for dependent drop down

    Details is here Krejee dependent dropdown for yii2

    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'=>'', 'name'=>''],
    // ['id'=>'', 'name'=>'']
    // ]
    echo Json::encode(['output'=>$out, 'selected'=>'']);
    return;
    }
    }
    echo Json::encode(['output'=>'', 'selected'=>'']);
    }
    

提交回复
热议问题