How to set selected with dropDownList?

In my ActiveForm I have this field:


$listOfItems = [

  'a' => 'a',

  'b' => 'b',

  'c' => 'c',

  'd' => 'd',

  ''  => ''

];


echo $form->field($model, 'theItem')->dropDownList($listOfItems, ['maxlength' => 100]);

If $model->theItem is null I’d like to select an element of $listOfItems as a preselected value. I don’t want to use ‘prompt’, I want a default value. How can this be done easily? I’d like to select with the key in the array.

Something like this would be nice:


echo $form->field($model, 'theItem')->dropDownList($listOfItems, ['maxlength' => 100])->select('a');

But this is not possible, unfortunately.

Try the following code:

I needed to show Mumbai as default selection and my key-value pair was ‘MUM’=>‘Mumbai’;

It worked for me, you can also try it in yourcase.

<?php echo $form->dropDownList($model,‘city’,Yii::app()->params[‘city’],array(‘options’ => array(‘MUM’=>array(‘selected’=>true)))) ?>

Do like if my solutions are helping you out. :D

This is Yii 1.1, right? In Yii 2.0 dropDownList can take only two parameters.

You can try it in controller/action before render the view for both version…




$model->theItem = 'a';



Yeah, I think this is the way to do it. Preparing the model for the view. This is like with the typical load & save calls in create or update actions: if one of them fails the so far populated model will be passed to the view. So why not preparing the model with default values, especially when an object should be created?

Thanks, I think this is it. If no one provides better solutions…

Thank you for the great solutions provided above. Without this I would have spent hours trying to figure this out.