Search code examples
formssymfony

Symfony check form field exist inside controller


Is there a way to check if a form field exist inside a controller?

I have a few submit buttons but depending on the data in the object the associated one will be shown and created.

FormType.php

$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
    /** @var ObjectInfo $tab */
    $tab = $event->getData();
    $form = $event->getForm();

    if (some condition) {
        //No Value has been set or NULL
        $form->add('submit_second', 'submit', array(
            'label' => 'submit',
        ))
    }

controller.php

 if ($overviewForm->get('submit_second')->isClicked()) {
     // do something
 }

I have also tried

if (
    !is_null($overviewForm->get('submit_second')) && 
    $overviewForm->get('submit_second')->isClicked()
) {

on submit I get

Error

Child "submit_second" does not exist.

Solution

  • If $form->has('field') (suggested by @jahller) does work in Symfony 6.3 (maybe also in older versions).