方案:我有2所选择的形式。 当用户从第一个选择的东西,第二个选择被用新值填充。 这部分工作正常。
但形式没有得到验证,因为它包含了一些选择,没有在最初的形式允许的。
形成:
<?php
class MyType extends AbstractType
{
private $category;
public function __construct($category = null)
{
$this->category = $category;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('category', 'choice', array(
'choices' => array(
'foo' => 'foo',
'bar' => 'bar'
)
);
$builder->add('template', 'choice', array(
'choices' => $this->loadChoices()
);
}
private function loadChoices()
{
// load them from DB depending on the $this->category
}
}
最初,类别为foo
。 所以foo的模板得到加载并设置为选择。 但是,如果用户选择bar
,酒吧模板得到加载。 但形式仍然有foo的选择,不验证。
什么是解决这个的最好方法?
我发现了一个办法是刚刚重新开始在控制器中的表格:
<?php
$form = $this->createForm(new MyType());
if ($request->getMethod() === 'POST') {
if ($request->request->has($form->getName())
&& isset($request->request->get($form->getName())['category'])) {
$form = $this->createForm(new MyType($request->request->get($form->getName())['category']));
}
// ...
}
这工作,而是因为它抛出我无法测试它IllegalArgumentException
设定值时,只是假设默认。 有没有更好的解决方案呢? 提前致谢!