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:
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.