-1

in Yii2 I’m trying to choose a specific option with an Html::dropDownList that uses optgroup. I’m able to create the dropdown html just fine using a nested array but how do I select one of the choices? What do I use as the $selection value?

Here is the line of code that I'm currently using. If leave the selection blank, it all works fine, but as soon as I try to select a specific value, I can't get it to work.

echo Html::dropDownList(
    'criteria',
    ['Page 1']['107141'],
    [
        'Page 1' => [
        '107145' => 'Q1: some text',
        '107141' => 'Q9: some text',
        '107142' => 'Q10:  some text',
        '107143' => 'Q11:  some text',
        '107164' => 'Q14: some text',
        ],
        'Page 2' => [
        '107195' => 'some text',
        ],
    ],
    [
        'prompt' => [
            'text' => 'Choose criteria',
            'options' => []
        ],
        'id' => 'criteriaSelector',
        'class' => 'criteriaSelector',
        'required' => 'required',
    ]
);

Here is the Yii documentation for the dropdownlist but I can't figure out what to do next: https://www.yiiframework.com/doc/api/2.0/yii-helpers-basehtml#dropDownList()-detail

Thank you!

Littlebob
  • 155
  • 4
  • 15
  • Hope it will helps : https://stackoverflow.com/questions/27581003/yii2-dropdown-selected-value – Serghei Leonenco Aug 22 '21 at 00:43
  • The second value of method `$selection` accepts `string|array|null` means` The selected value(s). String for single or array for multiple selection(s).` – SiZE Aug 22 '21 at 06:21

1 Answers1

0

For some reason I kept thinking that the the selection needed to be an array element but, of course, since the dropdown option name has to be unique, the selection only needs to be a string. Here is the solution:

echo Html::dropDownList(
    'criteria',
    '107141',
    [
        'Page 1' => [
        '107145' => 'Q1: some text',
        '107141' => 'Q9: some text',
        '107142' => 'Q10:  some text',
        '107143' => 'Q11:  some text',
        '107164' => 'Q14: some text',
        ],
        'Page 2' => [
        '107195' => 'some text',
        ],
    ],
    [
        'prompt' => [
            'text' => 'Choose criteria',
            'options' => []
        ],
        'id' => 'criteriaSelector',
        'class' => 'criteriaSelector',
        'required' => 'required',
    ]
);
Littlebob
  • 155
  • 4
  • 15