据我所知,表单助手魔法无法区分这两个字段,您要么必须单独传递列表,要么使用自定义表单助手。
使用options 选项
单独传递列表时,您只需使用options option,如有必要,CakePHP 将根据请求中传递的值自动选择适当的列表条目。
控制器
$tableOneFoos = array('a', 'b', 'c');
$tableTwoFoos = array('x', 'y', 'z');
$this->set(compact('tableOneFoos', 'tableTwoFoos'));
查看
$this->Form->input('TableOne.0.foo', array('type' => 'select', 'options' => $tableOneFoos));
$this->Form->input('TableOne.1.foo', array('type' => 'select', 'options' => $tableOneFoos));
$this->Form->input('TableOne.2.foo', array('type' => 'select', 'options' => $tableOneFoos));
$this->Form->input('TableTwo.0.foo', array('type' => 'select', 'options' => $tableTwoFoos));
$this->Form->input('TableTwo.1.foo', array('type' => 'select', 'options' => $tableTwoFoos));
$this->Form->input('TableTwo.2.foo', array('type' => 'select', 'options' => $tableTwoFoos));
就是这样,在使用提交的数据呈现表单时应该按预期选择值。
自定义表单助手
表单助手检查字段名的camelCased plurals 变量名(请参阅FormHelper::_optionsOptions()),不考虑模型名称,因此在您的情况下它将查找foos,那就是为什么你以这个列表结束所有输入。
您可以覆盖该方法并实施使用模型名称的附加检查,以便帮助程序查找 tableOneFoos 和 tableTwoFoos 等变量。
这是一个未经测试的!示例:
App::uses('FormHelper', 'View/Helper');
class MyFormHelper extends FormHelper {
protected function _optionsOptions($options) {
$options = parent::_optionsOptions($options);
if (!isset($options['options'])) {
// this is where the magic happens, an entity name like
// `Model_field` is turned into a variable name like
// `modelFields` which is then used to lookup the view vars.
$entityName = $this->model() . '_' . $this->field();
$varName = Inflector::variable(
Inflector::pluralize(preg_replace('/_id$/', '', $entityName))
);
$varOptions = $this->_View->get($varName);
if (is_array($varOptions)) {
if ($options['type'] !== 'radio') {
$options['type'] = 'select';
}
$options['options'] = $varOptions;
}
}
return $options;
}
}
然后您可以将tableOneFoos 和tableTwoFoos 传递给视图,而不使用options 和type 选项作为输入:
控制器
$tableOneFoos = array('a', 'b', 'c');
$tableTwoFoos = array('x', 'y', 'z');
$this->set(compact('tableOneFoos', 'tableTwoFoos'));
查看
$this->MyForm->input('TableOne.0.foo');
$this->MyForm->input('TableOne.1.foo');
$this->MyForm->input('TableOne.2.foo');
$this->MyForm->input('TableTwo.0.foo');
$this->MyForm->input('TableTwo.1.foo');
$this->MyForm->input('TableTwo.2.foo');
只要没有以 HABTM 方式使用的 TableOneFoo 或 TableTwoFoo 模型,这应该可以工作,因为它们的字段最终会使用相同的变量名称,即 tableOneFoos 和 tableTwoFoos。