Items in custom dropdown menu not working properly in Yii 2
P粉268284930
P粉268284930 2023-09-05 22:16:18
0
1
582
<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>
P粉268284930
P粉268284930

reply all(1)
P粉801904089

To achieve the desired output, where each item in the dropdown is represented by a single <option> tag with the specified label, value, and style, you need to modify your code as follows: In your view file, update the customDropDown function call to correctly pass the items array:

<?= $form->customDropDown($dpForm, 'color', [
        [
            'label' => 'red',
            'value' => 'red',
            'options' => [
                'style' => 'color: red'
            ]
        ],
        [
            'label' => 'blue',
            'value' => 'blue',
            'options' => [
                'style' => 'color: blue'
            ]
        ],
    ]
); ?>
Updated method:
public function customDropdown($model, $attribute, $items = [], $options = [])
{
    $value = Html::getAttributeValue($model, $attribute);

    $field = $this->field($model, $attribute);

    $options['options'] = array_column($items, 'options');
    $options['prompt'] = '';

    return $this->staticOnly ? $field : $field->dropDownList(array_column($items, 'label', 'value'), $options);
}
In this updated version, we pass the $options array directly to the dropDownList method and use array_column to extract the label-value pairs from the $items array
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template