因功能需求,需要用到联动,特此记录分享

一、视图中

<div class="main-form">

    <?php $form = ActiveForm::begin(); ?>


    <?= $form->field($model, 'cid')->dropDownList(
        \common\models\service\common\Category::getCateOptions(),
        [
            'prompt' => '请选择单位',
            'onchange'=>'
                $.post("/carousel/main/cate?id='.'"+$(this).val(),function(data){
                    $("select#main-aid").html(data);
                });',
        ]
    )->hint('父级,必选') ?>
    <?= $form->field($model, 'aid')->dropDownList( \common\models\service\common\Category::getCateOptions(), ['prompt' => '请选择子级']) ?>
    <div class="form-group">
        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

二、控制器

ublic function actionCate($id)
{
    $departments = Category::find()
        ->where(['parent_id' => $id])
        ->asArray()
        ->all();

    if(!$departments){
        echo "<option value='" . 0 . "'>"  . "</option>";
    }
    foreach ($departments as $department) {
        echo "<option value='" . $department['id'] . "'>" . $department['name'] . "</option>";
    }
}

三、实现效果

clipboard.png


双子城
46 声望6 粉丝

just do it!