Answer the question
In order to leave comments, you need to log in
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();?>
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>";
}
}
Answer the question
In order to leave comments, you need to log in
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();
]);
}
$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 questionAsk a Question
731 491 924 answers to any question