Issue
I want to modify some form fields depending on submitted data so in the form class I did:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('year', ChoiceType::class, [
'choices' => ['Year' => '-1'] + array_combine(range(date('Y'), date('Y') - 19), range(date('Y'), date('Y') - 19)),
'label' => false,
])
->add('make', ChoiceType::class, ['choices' => ['Make' => '-1'], 'label' => false])
->add('model', ChoiceType::class, ['choices' => ['Model' => '-1'], 'label' => false]);
//...
$builder->get('year')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) {
$year = $event->getForm()->getData();
$makes = $year === '-1' ? ['Make' => '-1'] : $this->customService->getMakes();
$event->getForm()->getParent()
->add('make', ChoiceType::class, ['choices' => $makes, 'label' => false]);
}
);
$builder->get('make')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) {
$make = $event->getForm()->getData();
$models = $make === '-1' ? ['Model' => '-1'] : $this->customService->getModels();
$event->getForm()->getParent()
->add('model', ChoiceType::class, ['choices' => $models, 'label' => false]);
}
);
}
However, even when I submit the make
field, the second listener is never executed, so I'm not able to modify the model
field. Any idea?
Solution
The problem seems to be that when modifying the make
field in the year
field event listener, then the make
field event listener is never called. I found a way to make it work:
private $makes;
private $models;
public function buildForm(FormBuilderInterface $builder, array $options)
{
//...
$builder->get('year')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) {
$year = $event->getForm()->getData();
$this->makes = $year === '-1' ? ['Make' => '-1'] : $this->customService->getMakes();
}
);
$builder->get('make')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) {
$make = $event->getForm()->getData();
$this->models = $make === '-1' ? ['Model' => '-1'] : $this->customService->getModels();
$event->getForm()->getParent()
->add('make', ChoiceType::class, ['choices' => $this->makes, 'label' => false, 'data' => $make]);
}
);
// Same with model field
}
Answered By - Manolo
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.