M
M
Maxim Osadchy2018-02-26 23:30:25
Yii
Maxim Osadchy, 2018-02-26 23:30:25

How to pull up the necessary data in a select based on another select?

Hello!
The essence of the problem is as follows:
There is a select, id is passed to value, it is necessary to generate a second select on the onchange of this select and transfer data from the database with the corresponding id to it.
How I did it: I
wrote a method in the controller with a json return, on onchange I access it via ajax and substitute the received data into a new select.
Why I don’t like this method:
When the page is reloaded, the second select disappears (because there was no ajax call), the select is not displayed through ActiveForm, but I need to save the received data to the database, of course, you can substitute the desired id, but it turns out some kind of crutch , whether.
In general, you need to transfer data in select depending on the selected item in the previous select, any ideas?
Thank you.
The code:

$form->field($model, 'goodMaterial')->dropDownList($goodItems)

<div class="goodAttribute"></div>
Getting and generating a new select:
$(function(){
                        var good_attrs
                        $('#goodmaterial').on('change', function(){
                            var goodId = this.value;
                            $.ajax({
                                url:"good-attribute",
                                type:"GET",
                                data: {id: goodId},
                                success: function(data) {
                                     good_attrs = jQuery.parseJSON(data);
                                     $('.goodAttribute').html('<span>Атрибут:</span><select name="" id=""></select>');
                                     good_attrs.forEach(function(element) {
                                        $('.goodAttribute select').html('<option value="'+element['attribute']+'">'+element['name']+'('+element['attribute']+')'+'</option>');
                                    });
                                   
                                }
                            });
                        });
                    });

The controller method itself is simple:
public function actionGoodAttribute($id)
    {
        $data =Good::find()->where(['category_id' => $id])->asArray()->all();
        return json_encode($data);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2018-02-27
@slo_nik

Make a second select on the form
And substitute values ​​there. Return an array from the server, as for the first one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question