Kosmos
Kosmos

Reputation: 333

How delete optgroup element from dropdown in Yii2 form

I am generating a DropDownList element in Yii2 with ActiveForm. My code is:

$form->field($model, 'job_type_id')
     ->dropDownList([ArrayHelper::map(JobsTypes::find()->all(), 'id', 'type_name' )])
     ->label('Job type')

But this generates the following HTML code:

<select name="Jobs[job_type_id]" class="form-control" id="jobs-job_type_id">
<optgroup label="0">
<option value="1">Sites</option>
<option value="2">Marketing</option>
</optgroup>
</select>

Why is there an optgroup element? This is not required. How do I delete this element from code?

When using

Html::activeDropDownList($model, 'id', ...);

the Html is generated correctly, but this element doesn't have a label() method.

Upvotes: 1

Views: 1150

Answers (1)

topher
topher

Reputation: 14860

The reason you are getting an optgroup is because you have wrapped the ArrayHelper::map... in an array and as such are passing in an array of arrays into the dropdown. As such the parameter being passed into the dropdown is of the form:

array(
    0 => array(
        1 => "Sites",
        2 => "Marketing",
        ...
    )
)

If nested arrays are passed into dropDownList, the sub arrays are treated as an optgroup with the corresponding keys of the outer array as the opt-group labels. The optgroup label is 0 since the result of ArrayHelper::map() is the first element of the array.

To fix this pass the ArrayHelper::map... without the square brackets around it:

$form->field($model, 'job_type_id')
     ->dropDownList(ArrayHelper::map(JobsTypes::find()->all(), 'id', 'type_name' ))

Upvotes: 4

Related Questions