I try to create dropdown-list with Yii, using listData and activeDropDownList.
I use the examples found on the web, but it refuses to create the optgroups for me.
$data = CHtml::listData(MyModel::model()->getEntries(0), 'id', 'text', 'group');
Generates an array as expected:
Array([group1] => Array([10]=>FirstEntry, [20]=>SecondEntry),
[group2]=>Array([30]=>firstEntryGroup2, [40]=>firstEntryGroup2))
And so on. So it's an associative array filled with sub-arrays...
But when I use
echo CHtml::activeDropDownList($model, 'dropdownName', $data);
All I get is a flat dropdown without the optgroups. Just the entries from the sub-arrays...
Yii 1.1.6 (I read something about safe-attributes and tried to implement it, but with no success...
One of solutions is anonymous function.
The old answer below is incorrect. Sorry. You create optgroups using a 'group' attribute in your drop down data array.
array( array('id'=>256,'text'=>'TV','group'=>'Electrical'), array('id'=>257,'text'=>'Radio','group'=>'Electrical'), );
http://www.yiiframework.com/forum/index.php/topic/6903-how-can-i-generate-a-select-list-with-optgroup/
Old answer:
There is a great gist here that shows how do create what you're after: https://gist.github.com/StandardNerd/2909111
<?php echo CHtml::dropDownList('Cars', 'car_id', array( 'Mazda'=>array( 'mazda-rx7'=>'RX7', 'mazda-rx5'=>'RX5', ), 'Volvo'=>array( 'volvo-b9tl'=>'B9TL', 'volvo-l90e-radlader'=>'L90E Radlader', ), )); ?>
You're currently using an activeDropDownList which should only be different because you add your $model variable instead of 'Cars' and tweak the function