M
M
Maxim Lagoysky2017-07-25 14:45:35
Yii
Maxim Lagoysky, 2017-07-25 14:45:35

Yii2 dependent select what is wrong?

I make dependent selects. The first one shows the brands in the second model depending on the selected brand.
Here is the code.

<?php $form = ActiveForm::begin(['options' => ['class' => 'col_16 user_card_wrapper']]);?>
              <?= $form->field($model, 'car_mark')->dropDownList(
                  ArrayHelper::map(MarkCar::find()->all(), 'id', 'mark'),
                  [
                      'prompt' => 'Select',
                      'onchange' => '
                        $.post( "/ajax/Ajax?id='.'"+$(this).val(), function(data){
                          $("#searchform-car_model").html(data);
                        } );
                        '
                  ]);
              ?>
              <?= $form->field($model, 'car_model')->dropDownList(
                  ['prompt' => 'Select',]);
              ?>
              <?php ActiveForm::end();?>

Here is the ajax function itself
public function actionAjax($id){
        echo 'asdasdasdas';
        $count_model = ModelCar::find()
            ->where(['id_mark' => $id])
            ->count();
        $car_model = ModelCar::find()
            ->where(['id_mark' => $id])
            ->all();
        echo "<option value = ''>Select</option>";
        if($count_model > 0){
            foreach ($car_model as $key){
                echo "<option value='".$key->id."'>".$key->model."</option>";
            }
        }
        else{
            echo "<option></option>";
        }
    }

I do everything according to my old working example, but here it refuses to work. The most interesting thing is that it returns me a full copy of the page. ajax itself works.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2017-07-26
@webinar

Why $.post? Isn't it easier:
And html in the controller is hellish heresy. Use renderAjax, this will solve the issue with

public function actionAjax($id){
       return $this->renderAjax('_some_view',[
                  'model' => ModelCar::find()
            ->where(['id_mark' => $id])->all();
       ]);
    }

render - page with layout, renderAjax - only what is in view.
And I instead of $models->count();yuzat count($models);Why 2 requests to do? And in your case, you can if(isset($models[0])){not even measure it, but theoretically it should work faster. Although you can also if(is_array($models)){, if memory serves, then you can evenif($models){

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question