2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Are you sure about $builder->getData(). As far as I can tell the only way to get the forms data during the build process is to use a form event which involves making a listener and what not.
Please notice that it's called on builder, not form. It's not the same getData that you have on your mind. This is initial data that you pass as 2nd param to createForm method or via data item in options array (3rd param).
That looks sweet. So your answer is that I can customize form logic inside? And this version you suggested is recommended? Please clarify answer and I will assign as correct one :)
Yes, it makes your form reusable and cosistent with the entity. Please also note that this logic is not a business rule, but the way you build the form, so it perfectly fits to be encapsulated inside the form class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.