2012-07-19 58 views
1

我有一个下拉列表,其中显示“产品类别”列表在下拉列表中显示多个值,CakePHP

问题是,存在多个同名产品类别。

每个产品类别都有一个关联的“系统”,所以我的问题是,有没有办法修改:

echo $this->Form->input('product_cat_id'); 

这表明Product Category显示System >> Product Category

回答

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 

T他的作品适合我!