0

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.

NikiC
  • 95,987
  • 31
  • 182
  • 219
MSK90
  • 21
  • 5
  • Hard to tell from just that - could you post your entities including the relationship definitions? – Bananaapple Oct 21 '19 at 14:58
  • Thanks for your answer. My problem is resolved. Technically, I make a route that loads the categories when I get on the page, then a route called by ajax that will return a JSON to dynamically populate the second list. – MSK90 Oct 22 '19 at 07:34

0 Answers0