M
M
Maxim Lagoysky2017-03-23 20:12:51
Yii
Maxim Lagoysky, 2017-03-23 20:12:51

depdroplist not working in yii2?

Good evening everyone, I'm trying to make 2 dropdown lists that depend on each other.
There are 2 tables category and sub_category. In the category table there are 2 fields id and category (category name), in the sub_category table there are 3 fields id, id_category, sub_category (subcategory name). Here is the actual view

<? $category = Category::find()->all()?>
        <? $category = ArrayHelper::map($category, 'id', 'category');
        $params = ['prompt' => 'Select category']?>
    <?= $form->field($model, 'category')->dropDownList($category, $params) ?>

        <?= $form->field($model, 'sub_category')->widget(DepDrop::classname(),[
            'options' => ['id','sub_category'],
            'pluginOptions' => [
                'depends' => ['id'],
                'placeholder' => 'select',
                'url' => Url::to(['user/sub'])
            ]
        ]) ?>

And here is the controller
public function getSubCategory($id) { // could be a static func as well
       $sub_category = SubCategory::find()->where(['id_category' => $id])->asArray()->all();
       return ArrayHelper::map($sub_category, 'id', 'sub_category','id_category');
   }
   public function actionsub() {
       $out = [];

       if (isset($_POST['depdrop_parents'])) {
           $parents = $_POST['depdrop_parents'];
           if ($parents != null) {
               $id = $parents[0];
               $out = SubCategory::getSubCategory($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'=>'']);
   }

I can't figure out what's wrong? The page is displayed without errors. I don't know how to track ajax errors(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2017-03-23
@lagoy

Good evening.
To track down ajax errors in browser F12, "network" tab.
Or use yii\httpclient\debug\HttpClientPanel
Well, the form with the action needs to be changed a bit.
Or rather, you can not use an additional widget at all, everything is much simpler.
ps And if you are using yii2, then use its full capabilities.
In particular, to get data from $_POST, use Yii::$app->request->post().
Check that ajax has arrived use Yii::$app->request->isAjax

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question