I'm trying to implement a dynamic form with Symfony 4.3 based on the official documentation.
To simplicify, I have 3 entities: product, category and subcategory related to each other with OneToMany relationships as follows: a category can have multiple subcategories and a subcategory can have multiple products. By choosing a category (sport for example), I wanted to have the list of sport sub-categories displayed in the following field.
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nom')
->add('categorie', EntityType::class, [
'class' => 'App\Entity\Categorie',
//'placeholder' => '',
])
;
$formModifier = function (FormInterface $form, Categorie $categorie = null) {
$subcategories = null === $categorie ? [] : $categorie->getSubcategories();
//var_dump($subcategories);
$form->add('subcategorie', EntityType::class, [
'class' => 'App\Entity\Subcategorie',
//'placeholder' => '',
'choices' => $subcategories,
]);
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
// this would be your entity
$data = $event->getData();
//var_dump($data);
//die;
$formModifier($event->getForm(), $data->getCategorie());
}
);
$builder->get('categorie')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
$categorie = $event->getForm()->getData();
$formModifier($event->getForm()->getParent(), $categorie);
}
);
//...
}
My concern is that I can not getthe value of my dumps ($data and $subcategories): they are always on NULL. So, I can not find my subcategories in the form.
I'm asking because I'm really blocked for a while and I can not find the bug in this code based on the Symfony documentation.