模板表单元素应该是:
$ingredientOptions = array('Potato','Peanut','Parsley');
echo $this->Form->input('FavouriteIngredients', array('multiple' => true, 'options' => $ingredientOptions);
echo $this->Form->input('AllergicIngredients', array('multiple' => true, 'options' => $ingredientOptions);
这会创建两个(难看的)多个选择框,每个选择框都有一个由options数组中的元素组成的列表,其中没有一个被选中。
为了设置初始值,我在控制器中尝试了一些事情,但没有成功:
$this->set('FavouriteIngredients',array(1,2));
$this->request->data['FavouriteIngredients'] = array(1,2);
这些多重选择是针对客户模型中定义的两个HABTM关系的:
class Customer extends AppModel {
public $hasAndBelongsToMany = array(
'FavouriteIngredients' =>
array(
'className' => 'Ingredient',
'joinTable' => 'customer_ingredients_favourite'
);
'AllergicIngredients' =>
array(
'className' => 'Ingredient',
'joinTable' => 'customer_ingredients_allergic'
);
);
}
实际上,生产中的问题是这些值不存在于options数组中。
$this->request->data['Customer']['FavouriteIngredients'] = array(1,2);