Scenario: I have a form with 2 selects. When user selects something from the first select, the second select gets populated with new values. This part works fine.
But the form does not get validated since it contains some choices that are not allowed in the initial form.
Form:
<?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
}
}
Initially the category is foo
. So the templates for foo get loaded and set as choices. But if the user selects bar
, the bar templates get loaded. But the form still has the foo choices and does not validate.
What is the best way to solve this?
One way I found was to just reinitiate the form in the controller:
<?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']));
}
// ...
}
This works, but I cannot test it because it throws IllegalArgumentException
when setting the value and just assumes default. Is there any better solution to this? Thanks in advance!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…