How to use selected value in Html::dropDownList with optgroups?

Hi, I’m trying to select a specific value with Html::dropDownList which 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?

Thank you!

Hi @littlebob,

Could you show us your code to render the dropDownList?

Basically, you are to set the value (not the label) of the selected option to the $selection. There’s no difference regarding this whether your dropDownList is grouped or not.

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!

Try this instead.

   echo Html::dropDownList(
    	'criteria',
    	// ['Page 1']['107141'],
       '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',
    	    ],
    	],  

Yes, that solved the problem. 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.