Search code examples
phpformssymfonyformbuilder

Symfony2 - customizing FormType classes


I have few cases where I need to ugly customizing of my FormType classes.

First one is that I need to check if the state of user is active in this case disable possibility to edit username. But just adding disabled atribute is not protecting input to be not submitted. So I decided not to show username input field. I achieved it by passing boolean through options.

Controller:

$userForm = $this->createForm(UserType::class, $user, array(
    'is_active' => ($user->getState() == 'active')
));

And then in UserType class:

if ($options['is_active']) {
    $builder
        ->add('username', EmailType::class);
}

$builder
    ->add('firstName', TextType::class),
...

Second case is that I need to remove NotBlank() constraint and add 'required' => false attribute from FileType field when profile photo is uploaded. I achieved it in similar way by passing boolean through options.

Controller:

$userForm = $this->createForm(UserType::class, $user, array(
    'is_uploaded' => !empty($photo)
));

UserType class:

// achieved same way as previous problem

My questions would be:

  • What recommendations would be dealing with these kind of cases?
  • Is what I did correct and acceptable?
  • Is there a documentation or examples dealing with any of these cases?

Solution

  • You can move all this form configuration's logic into the form class.

    Since you pass $user entity into the form with:

    $userForm = $this->createForm(UserType::class, $user, array( // <- $user is passed
        'is_uploaded' => !empty($photo)
    ));
    

    You can access it in builForm method with:

        $user = $builder->getData();
    

    Then you can verify all the condifions inside the form and there's no need for making mess in controller.