我有一个下拉列表,其中显示了“产品类别”列表
问题是,有多个同名产品类别。
每个产品类别都有一个关联的“系统”,所以我的问题是,有没有办法修改:
echo $this->Form->input('product_cat_id');
显示Product Category
以显示System >> Product Category
答案 0 :(得分:1)
好的,我明白了。
我无法在视图级别轻松完成,所以我必须在控制器级别进行。
基本上,我的目标是构建如下所用的选项组:
$options = array(
'Group 1' => array(
'Value 1' => 'Label 1',
'Value 2' => 'Label 2'
),
'Group 2' => array(
'Value 3' => 'Label 3'
)
);
echo $this->Form->select('field', $options);
我认为最好在我的控制器中构建选项列表并将其传递给视图。
为此,我将此代码添加到控制器的操作中:
$systemCats = $this->Product->ProductCat->SystemCat->find('all');
$this->set('fieldOptions', buildFieldOptions($systemCats));
我创建了一个名为buildFieldOptions的函数,它使用完全关联的$ systemCats数组作为参数:
function buildFieldOptions($productCats, $systemCats) {
$optionsArray = array(); //empty options array
foreach ($systemCats as $systemCat) {
$productCatArray = array(); //empty product categories array
foreach($systemCat['ProductCat'] as $productCat){
$productCatArray[$productCat['id']] = $productCat['title'];
//fill product categories array
}
$optionsArray[$systemCat['SystemCat']['title']] = $productCatArray;
//fill options array with system category as a key
}
return $optionsArray;
}
完成的一个选择框现在具有以下选项:
SystemCategory
Product Category
Product Category
Product Category
SystemCategory
Product Category
Product Category
Product Category
这对我有用!