Answer the question
In order to leave comments, you need to log in
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>
$(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>');
});
}
});
});
});
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question