状況: dropDownList オブジェクト
で「選択した項目」を指定するのに問題があります。グループ化された dropDownList を使用しており、それぞれが多数の選択項目を含む多数の optgroup 項目を持っています。前述のように、各アイテムは optgroup 内にあるため、課題はデフォルトで選択されたアイテムを指定する方法を見つけようとすることです。
質問:
グループ化されたフォームを使用する場合、デフォルトの選択項目をどのように設定しますか? または以下のコードが機能しないのはなぜですか?
いくつかのコード:
<?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>
//...