Symfony 4.2 event POST_SUBMIT is returning null

152 views Asked by At

Im doing 3 forms in Symfony 4.2.5 all with the same code when load states and cities (estados and municipios) but only this form is making me crazy because has the same code that all but doesnt work it always return null in "municipio", and when I print $request it has municipio=1 but in $form->isValid() says that municipio is null and it started when I added FormEvents

Please if someone could help me I'll be grateful, I inspected all my code but this is where its break.

$builder->get('estado')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
        $estado = $event->getForm()->getData();

        if (null == $estado) {
            $event->getForm()->getParent()->add('municipio', EntityType::class, [
                'class' => 'App\Entity\Municipio',
                'required' => true,
                'placeholder' => '== Selecciona un municipio 1==',
                'choices' => []
            ]);
        } else {
            $event->getForm()->getParent()->add('municipio', EntityType::class, [
                'class' => 'App\Entity\Municipio',
                'required' => true,
                'placeholder' => '== Selecciona un municipio 2 ==',
                'choices' => $estado->getMunicipios()
            ]);
        }
    }
    );
1

There are 1 answers

0
EsopMx On

I had duplicated my field, one in buildForm when add and other in the event and cause bad behaviour.

Symfony dont say that we can not add a field more than 1 time and no error is showing until I needed submit the form and my field was not recognized and always had null value.

I just deleted $builder->add('municipio') and all work fine.