Yii2 Select2多选依赖字段

时间:2016-11-20 22:43:06

标签: ajax yii2 select2

我该怎么做:我有两个多选字段Select2,第一个分支字段,第二个字段为工人。 当我选择分支机构时,在第二个领域我需要展示在这个分支机构工作的工人。

1 个答案:

答案 0 :(得分:0)

查看档案

<label><?= $model->getAttributeLabel('branch') ?></label>
    <?php echo Select2::widget([
        'name' => 'branch',
        'id' => 'branches',
        'theme' =>Select2::THEME_BOOTSTRAP,
        'value' => '',
        'data' => $branchList,
        'options' =>  [
            'placeholder' => Yii::t('app', 'Choose branch'),
            'multiple' => true,
        ],
        'pluginOptions' => [
            'tags' => true,
            'allowClear' => true,
        ],]);?>

    <label><?= $model->getAttributeLabel('Workers') ?></label>
    <?php echo Select2::widget([
        'name' => 'worker',
        'id' => 'workers',
        'theme' =>Select2::THEME_BOOTSTRAP,
        'value' => '',
        'data' => [],
        'options' =>  [
            'placeholder' => Yii::t('app', 'Choose workers'),
            'multiple' => true,
        ],
        'pluginOptions' => [
            'tags' => true,
            'allowClear' => true,
        ],]);
    ?>

JS

$("#branches").change(function(){
        change();    
    });

    function change() {        
        var selectValue = $("#branches").val();            
        $("#workers").empty();

        $.post( "'.Yii::$app->urlManager->createUrl('constructor/lists?id=').'"+selectValue,
                function(data){
                    $("#workers").html(data);
                }
            );

    };   

ConstructorController

public function actionLists($id)
    {
        if ($id != null) {
            $ids = explode(",", $id);
            foreach ($ids as $id_branch) {
                $workers = Report::getWorkers($id_branch);
                if (count($workers) > 0) {
                    foreach ($workers as $worker) {
                        echo "<option value='" . $worker . "'>" . $worker . "</option>";
                    }
                } else {
                    echo "'<option>-</option>'";
                }
            }
        }
    }