Sonata Admin and Dynamic Form

965 views Asked by At

I made several search but I still have a problem...

I want to make a dynamic form. I want to hydrate a select in function of an other select. This is my configureFormFields:

protected function configureFormFields(FormMapper $formMapper)
    {
        $emIndustry = $this->modelManager
                           ->getEntityManager('*\*\*\*\Entity\Industry')
        ;

        $query = $emIndustry->getRepository(*:Industry')
                            ->getFindAllParentsQueryBuilder()
        ;

        $formMapper
            ->add('company')
            ->add('industry', 'sonata_type_model', [
                'attr' => [
                    'onchange' => 'submit()',
                ],
                'query'    => $query,
                'required' => false,
            ])
            ->add('subIndustry', 'sonata_type_model', [
                'choices' => [],
                'required' => false,
            ])
        ;

        $builder = $formMapper->getFormBuilder();
        $factory = $builder->getFormFactory();
        $subject = $this->getSubject();
        $modelManager = $this->getModelManager();

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) use($formMapper, $subject, $emIndustry, $modelManager, $factory) {
            $form = $event->getForm();

            if(!is_null($subject->getIndustry())) {
                $query = $emIndustry->getRepository('*:Industry')
                    ->getFindChildrenByParentQueryBuilder($subject->getIndustry())
                ;

                $form
                    ->add(
                        $factory->createNamed('subIndustry', 'sonata_type_model', null, [
                            'class'    => '*\*\*\*\Entity\Industry',
                            'query'    => $query,
                            'required' => false,
                        ])
                    )
                ;
            }
        });
    }

When I change the value of the select Industry, no problem my form is submited. But nothing happend in second select subIndustry because : all attributes of my $subject object is null...

Have you any idea why ? Is there a best way to make a dynamic form ?

Thank's for your help.

AlexL

0

There are 0 answers