How to Define the Validation Groups to Use

How to Define the Validation Groups to Use

Validation Groups

If your object takes advantage of validation groups, you’ll need to specify which validation group(s) your form should use. Pass this as an option when creating forms in controllers:

  1. $form = $this->createFormBuilder($user, [
  2. 'validation_groups' => ['registration'],
  3. ])->add(...);

When creating forms in classes, add the following to the configureOptions() method:

  1. use Symfony\Component\OptionsResolver\OptionsResolver;
  2. public function configureOptions(OptionsResolver $resolver): void
  3. {
  4. $resolver->setDefaults([
  5. // ...
  6. 'validation_groups' => ['registration'],
  7. ]);
  8. }

In both of these cases, only the registration validation group will be used to validate the underlying object. To apply the registration group and all constraints that are not in a group, use:

  1. 'validation_groups' => ['Default', 'registration']

Note

You can choose any name for your validation groups, but Symfony recommends using “lower snake case” names (e.g. foo_bar) in contrast with the automatic validation groups created by Symfony, which use “upper camel case” (e.g. Default, SomeClassName).

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.