S
S
Silverviql2018-09-21 12:43:32
Yii
Silverviql, 2018-09-21 12:43:32

How to make dependent lists in a form?

Found an example how to implement dependent lists on yii2 using widget demos.krajee.com/widget-details/depdrop
Tried to use this example. gives an error message

POST localhost/zakaz/service 400 (Bad Request)

view:
$data = ArrayHelper::map(Service::find()->all(), 'id', 'title');
   <?= // Tagging support Single
            $form->field($model, 'description', ['options' => ['class' => 'col-sm-6']])->widget(Select2::classname(),[
                'name' => 'service',
                'data' =>$data,
                'language' => 'ru',
                'initValueText' => ['1'],
                'options' => [
                        'placeholder' => 'Select a service ...',
                    ],
                'pluginOptions' => [
                    'allowClear' => false,
                    'tags' => true,
                    'tokenSeparators' => [',', ' '],
                    'maximumInputLength' => 10
                ],
            ])->label(false) ?>

            <?= $form->field($model, 'service_params', ['options' => ['class' => 'col-sm-6']])->widget(DepDrop::classname(), [
                'type'=>DepDrop::TYPE_SELECT2,
                'pluginOptions'=>[
                    'depends'=>['zakaz-description'],
                    'placeholder' => 'Выберите категорию...',
                    'url' =>  Url::to(['/zakaz/service']),
                    'loadingText' => 'Загрузка категорий...',
                ]
            ])->label(false); ?>

controller:
public function actionService()
    {
        $out = [];
        if (isset($_POST['depdrop_parents'])) {
            $id_service = end($_POST['depdrop_parents']);
            $list = ServiceParameters::findAll(['description'=>$id_service]);
            $selected  = null;
            if ($id_service != null && count($list) > 0) {
                $selected = '';
                foreach ($list as $i => $model) {
                    $zakaz = Zakaz::findOne($model['id_zakaz']);
                    $category = User::findOne($model['id']);
                    $out[] = ['id' => $model['id'], 'name' => $zakaz->description.' ('.$category->username.')'];
                    if ($i == 0) {
                        $selected = $model['id'];
                    }
                }
                // Shows how you can preselect a value
                echo Json::encode(['output' => $out, 'selected'=>$selected]);
                return;
            }
        }
        echo Json::encode(['output' => '', 'selected'=>'']);
    }

If you go to the page localhost/zakaz/service
It gives
{"output":"","selected":""}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question