The Situation:
I’m having some trouble specifying a ‘selected item’ in a dropDownList object. I’m using a grouped dropDownList having a number of optgroup items which each contain a number of select items. The challenge is trying to find a way to specify the default selected item, because, as mentioned, each item is within an optgroup.
The Question:
How do you set the default selected item when using a grouped form? or Why does the below code not work?
Some Code:
<?php
// retrieve the parent categories first
$parents = Categories::model()->findAllByAttributes(array('idCategoryParent'=>0));
// prepare an array to hold parent categories as optgroups, and their child categories as selectable items
$categories = array("Select a Category Below");
// prepare an array to hold the location of the selected item (if any)
$selectedItemInfo = array();
foreach($parents as $parent) {
// retrieve the sub categories for this parent category
$children = Categories::model()->cache(Yii::app()->findAllByAttributes(array('idCategoryParent'=>$parent->idCategory));
// prepare an array to temporarily hold all sub categories for this parent category
$categoriesChildren = array();
// iterate over sub categories
foreach($children as $child) {
// Assign the category name (label) to its numeric id
// Example. '10' => 'Coffee Mugs'
$categoriesChildren[$child->idCategory] = $child->label;
/**** Important part
* we may on occasion have an 'id' as a url parameter
* if 'id' isset, and
* if the current sub category idCategory matches 'id'
* mark this sub category as the item we want selected in our dropDownList
*/
if(isset($_GET['id']) && $child->idCategory == $_GET['id']){
// store the location of the current sub category
$selectedItemInfo[0] = $parent->label;
$selectedItemInfo[1] = $child->idCategory;
}
}
/*** Another Important part
* here we assign the whole child categories array
* as a single element in our categories array
* that can be accessed by the category name (label)
* of the parent category.
* Passing this entire $categories array to our
* dropDownList will make it render as a grouped
* dropDownList with the groups as optgroup items.
*/
// Example. 'Kitchenware' => {array}
$categories[$parentLabel] = $categoriesChildren;
}
?>
<?php
// get our selected item
/**** Remember
* The element $selectedItemInfo[0] holds our parent category's string name (label)
* The element $selectedItemInfo[1] holds our child category's id
*/
$selectedItem = $categories[$selectedItemInfo[0]][$selectedItemInfo[1]];
// create an options array to inform dropDownList of our selected item
$options = array('options'=>array($selectedItem=>array('selected'=>true)));
?>
//...
<div class="row">
<?php echo $form->labelEx($model,'idCategory'); ?>
<?php echo $form->dropDownList($model,'idCategory', $categories, $options); ?>
<?php echo $form->error($model,'idCategory'); ?>
</div>
//...
Solved.
Just needed to set $model->idCategory before calling the dropDownList code. Like so: