我想将布尔值传递给我 DogForm
$dogForm = new DogForm(null, array("has_cats" => $this->getUser()->hasCats()));
$form = $this->createForm($dogForm, $dog);
Run Code Online (Sandbox Code Playgroud)
但在我做的时候DogForm
:
if (!isset($options['has_cats'])) {
throw new \Exception("Missing option has_cats, this option is mandatory");
}
Run Code Online (Sandbox Code Playgroud)
它总是给我这个错误.
所以我知道狗不应该有猫但是,我的has_cats
选择去了哪里?
谢谢.
Kri*_*ith 24
应该将选项传递给createForm()
方法,而不是传递给DogForm
构造函数:
$form = $this->createForm(new DogForm(), $dog, array('has_cats' => $cats));
Run Code Online (Sandbox Code Playgroud)
记住,你要"has_cats"添加到getDefaultOptions()
以及
sf_*_*anb 11
我将为那些阅读此内容的人添加一些最佳实践,因为当我提出问题时,OptionResolver不像现在那样先进:
不是"has_cats"
在表单构建器中检查选项的存在,而是最好:
public function setDefaultOptions(OptionResolverInterface $resolver)
{
$resolver->setRequired(array(
'has_cats',
));
$resolver->setDefaults(array(
'has_cats' => null,
));
}
Run Code Online (Sandbox Code Playgroud)
这样,如果省略传递"has_cats"
选项,则会抛出错误,因为您将选项标记为必需.
如果您需要更多信息,我建议您阅读选项解析器文档