Yii 2 dropDownList - no default selected
I am using Yii 2 ActiveForm trying to make option 7 the "default".
For this I need to use an array of options, but when I do this the html "selected" attribute is not shown at all when viewing the HTML source. I have no errors.
If I use other parameters like "label" it works as intended.
$form->field($model, 'date')->dropDownList($months, [
'options'=>array(
'7' => ['label' => 'JULY', 'selected'=>true],
),
]);
As per the docs any "valid" option is accepted, I assume "selected" is valid since this is an HTML dropdown?
This is what is generated:
<select id="log-date" class="form-control" name="Log[date]">
<option value="1">JANUARY</option>
<option value="2">FEBRUARY</option>
<option value="3">MARCH</option>
<option value="4">APRIL</option>
<option value="5">MAY</option>
<option value="6">JUNE</option>
<option value="7" label="label works fine">JULY</option>
<option value="8">AUGUST</option>
<option value="9">SEPTEMBER</option>
<option value="10">OCTOBER</option>
<option value="11">NOVEMBER</option>
<option value="12">DECEMBER</option>
</select>
source to share
-
The answer was given here: Yii2 dropDownList checkbox selected . You need to set the date attribute:
$model->date = 7; $form->field($model, 'date')->dropDownList($months);
-
There is also a discussion from the developers: dropDownList pre Choosing not rendering 'selected' They assume that you either define a default value for the attribute in the init () method or set it directly in the view (this is the same as the answer above). I also do it like this:
$model->priority = $model->isNewRecord ? 2 : $model->priority; $form->field($model, 'priority',[ 'options'=>['class'=>'col-xs-12 col-md-3'] ])->dropDownList($priorityList)
source to share