Items in custom dropdown menu not working properly in Yii 2
P粉268284930
2023-09-05 22:16:18
<p>I'm creating my own dropdown list function in Yii 2. I have created a function and a view and in the view I have multiple items in my dropdown form. </p>
<pre class="brush:php;toolbar:false;"><?= $form->customDropDown($dpForm, 'color', [
'items' =>
[
'label' => 'red',
'value' => 'red',
'options' => [
'style' => 'color: red'
]
]
[
'label' => 'blue',
'value' => 'blue',
'options' => [
'style' => 'color: blue'
]
]
]
</pre>
<p>The function I created is as follows (it uses and is located in ActiveForm): </p>
<pre class="brush:php;toolbar:false;"> public function customDropdown($model, $attribute, $items = [], $options = [])
{
$value = Html::getAttributeValue($model, $attribute);
$field = $this->field($model, $attribute, $options);
return $this->staticOnly ? $field : $field->dropDownList($items);
}
</pre>
<p>The problem is that when I open my dropdown, everything is an option or a group of options, not just the options with labels and styles. </p>
<p>The display effect in <em>Inspector</em> is as follows:</p>
<pre class="brush:html;toolbar:false;"><optgroup label='0'>
<option value="label">red</option>
<option value="value">red</option>
</optgroup>
<optgroup label="options">
<option value="style">color: red</option>
</optgroup>
</pre>
<p>And so on. The effect I want is as follows:</p>
<pre class="brush:html;toolbar:false;"><option value="red" style="color: red">red</option>
</pre>
<p>But I can't seem to achieve this effect. </p>
To achieve the desired output, where each item in the dropdown is represented by a single
Updated method: In this updated version, we pass the $options array directly to the<option>
tag with the specified label, value, and style, you need to modify your code as follows: In your view file, update thecustomDropDown
function call to correctly pass the items array:dropDownList
method and usearray_column
to extract the label-value pairs from the $items array