Yii2 dropdownList select default option

I am returning the cat_id value by GET in the url to tell my drop-down list which element should be selected. But it does not work.

<?= $form->field($model, 'cat_id')->dropDownList( ArrayHelper::map(DeviceCats::find() ->where(['is_deleted' => 'no'])->all(),'id','title') ,['options' => [$_GET['cat_id'] => ['selected'=>true]] , 'prompt' => ' -- Select Category --']) ?> 
+7
drop-down-menu yii2 yii2-advanced-app
source share
3 answers

Finally decided with an incredible change. Just changed the first letter of the selected capital (" selected " should be " Selected "). Here is the code:

 <?= $form->field($model, 'cat_id')->dropDownList( ArrayHelper::map(DeviceCats::find() ->where(['is_deleted' => 'no'])->all(),'id','title') ,['options' => [$_GET['cat_id'] => ['Selected'=>'selected']] , 'prompt' => ' -- Select Category --']) ?> 
+11
source share

"Selected" should be written with a capital "S":

 'options'=>['72'=>['Selected'=>true]] 
+10
source share

Just make sure your model has a cat_id property. Somewhere in your controller just

 $model->cat_id = filter_input_array(INPUT_GET, 'cat_id'); 

or

  $modelArray = filter_input_array(INPUT_GET, 'nameofmodel'); $model->cat_id = $modelArray['cat_id']; 

If you really want to do this, just like you, you might need to use the model name too.

  <?= $form->field($model, 'cat_id')->dropDownList(ArrayHelper::map(DeviceCats::find()->where(['is_deleted' => 'no'])->all(),'id','title'),['options' => [$_GET['SOMETHIGNHERE']['cat_id'] => ['selected'=>true]], 'prompt' => ' -- Select Category --']) ?> 
0
source share

All Articles