I have a form with (in the end) 3 Dropdown selections:
FieldA
FieldB
FieldC
with Options of FieldB dependent on the selection for fieldA and Options of FieldC dependent on the selection for fieldB
The Relations are:
EntityB ManyToMany EntityA
EntityC ManyToOne EntityB
Everything is working fine, execpt that on Submit the form is not valid with the Error being “This form should not contain extra fields” and the culprit being fieldC
what am I doing wrong?
here’s my code for the FormType:
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('fieldA', EntityType::class, [
'class' => EntityA::class,
'choice_label' => 'name',
'query_builder' => function(EntityARepository $a) {
return $a->createQueryBuilder('a')
->orderBy('a.name', 'ASC');
},
])
;
$builder->get('fieldA')->addEventListener(
FormEvents::POST_SUBMIT,
function(FormEvent $event) {
$form = $event->getForm();
$this->setupFieldB(
$form->getParent(),
$form->getData()
);
}
);
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event) {
$data = $event->getData();
if (!$data or !isset($data['fieldA'])) {
return;
}
$this->setupFieldB(
$event->getForm(),
$data['fieldA']
);
}
);
if ($builder->has('fieldB')) {
$builder->get('fieldB')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) {
$form = $event->getForm();
$this->setupFieldC(
$form->getParent(),
$form->getData()
);
}
);
}
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$data = $event->getData();
if (!$data or !isset($data['fieldB'])) {
return;
}
$this->setupFieldC(
$event->getForm(),
$data['fieldB']
);
}
);
}
private function setupFieldB(FormInterface $form, ?string $selectedfieldA)
{
if (is_null($selectedfieldA)) {
$form->remove('fieldB');
$form->remove('fieldC');
return;
} else {
$fieldA = $this->EntityARepository->findOneBy(['name' => $selectedfieldA]);
$form
->add('fieldB', EntityType::class, [
'class' => EntityB::class,
'query_builder' => function (EntityBRepository $b) use ($fieldA) {
return $b->createQueryBuilder('b')
->andWhere(':fieldA MEMBER of b.fieldAs')
->setParameter('fieldA', $fieldA)
->orderBy('b.name', 'ASC');
},
'choice_label' => 'name',
]);
}
}
private function setupFieldC(FormInterface $form, ?string $selectedFieldB)
{
if (is_null($selectedFieldB)) {
$form->remove('fieldC');
return;
} else {
$fieldB = $this->fieldBRepository->findOneBy(['name' => $selectedFieldB]);
$form
->add('fieldC', EntityType::class, [
'class' => EntityC::class,
'query_builder' => function(EntityCRepository $c) use ($fieldB) {
return $c->getQueryBuilderWithFilter(['fieldB' => $fieldB]);
},
'choice_label' => 'name',
]);
}
}