Issue when attempting to submit form with a ChoiceType using Symfony

  Kiến thức lập trình

I have the following code which does not work while attempting to submit the form:

namespace AppForm;

use AppEntityStatus;
use AppEntitySignal;
use SymfonyComponentFormAbstractType;
use DoctrineORMEntityRepository;
use DoctrineORMQueryBuilder;
use SymfonyBridgeDoctrineFormTypeEntityType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentFormExtensionCoreTypeChoiceType;
use SymfonyComponentFormChoiceListChoiceList;
use SymfonyComponentFormFormEvents;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentFormFormEvent;
use SymfonyComponentFormFormInterface;
class SignalType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder

            
            ->add('actionPlan')
            ->add('actionPlanStatus', EntityType::class, [
                'mapped' => false,
                'class' => status::class,
                'query_builder' => function (EntityRepository $er): QueryBuilder {
                    return $er->createQueryBuilder('u');
                },
                'choice_label' => 'name',
            ])
            ->add('deadline')   
        ;
        $formModifier = function(FormInterface $form, Signal $actionPlanStatus = null){   
        };
        $builder->get('actionPlanStatus')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier){
                $actionPlanStatus = $event->getForm()->getData();
                $formModifier($event->getForm()->getParent(), $actionPlanStatus);
            }
        );
    }
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Signal::class,
        ]);
    }
}

In the controller am using the following code:

public function yourAction(Request $request): Response
    {
        $form = $this->createForm(SignalType::class);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // Handle form submission
        }

        return $this->render('_form.html.twig', [
            'form' => $form->createView(),
        ]);
    }

When testing, I get the following error:

AppFormSignalType::AppForm{closure}(): Argument #2 ($actionPlanStatus) must be of type ?AppEntitySignal, AppEntityStatus given, called in C:laragonwwwabcsrcFormSignalType.php on line 64

Could you please help idetifiying the root cause of the issue and how to fix it in order to let the dropdown option save into the database.

Expecting to have the form saved into the database.

New contributor

Fatma Ellouze is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT