简体   繁体   中英

Yii 2 dropDownList - Default value not being selected

I'm using Yii 2 ActiveForm, trying to make option 7 "default".

To do this, I have to use the options array, but when I do so, my html attribute "selected" is not being rendered at all when viewing the HTML source. I get no errors.

If I use other options, such as "label" it works as intended.

$form->field($model, 'date')->dropDownList($months, [
'options'=>array(
'7' => ['label' => 'JULY', 'selected'=>true],
),
]);

According to the docs, any "valid" option is accepted, I assume "selected" is valid as it's a HTML dropdown list?

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>
  1. It was answered here: Yii2 dropDownList mark option selected . You need to set the date attribute:

     $model->date = 7; $form->field($model, 'date')->dropDownList($months); 
  2. There is also discussion from developers: dropDownList pre Selection not rendering 'selected' They propose that you either define default value for attribute in init() method or set it directly in view (this is same as 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) 

In my situation the code for yii2 is:

<?= $form->field($model, 'status')->dropDownList($order_statuses, ['value' => !empty($model->status) ? $model->status : 1]); ?>

where 1 is id for default selected value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM