How to Dynamically Configure Form Validation Groups

How to Dynamically Configure Form Validation Groups

Sometimes you need advanced logic to determine the validation groups. If they can’t be determined by a callback, you can use a service. Create a service that implements __invoke() which accepts a FormInterface as a parameter:

  1. // src/Validation/ValidationGroupResolver.php
  2. namespace App\Validation;
  3. use Symfony\Component\Form\FormInterface;
  4. class ValidationGroupResolver
  5. {
  6. private $service1;
  7. private $service2;
  8. public function __construct($service1, $service2)
  9. {
  10. $this->service1 = $service1;
  11. $this->service2 = $service2;
  12. }
  13. public function __invoke(FormInterface $form): array
  14. {
  15. $groups = [];
  16. // ... determine which groups to apply and return an array
  17. return $groups;
  18. }
  19. }

Then in your form, inject the resolver and set it as the validation_groups:

  1. // src/Form/MyClassType.php;
  2. namespace App\Form;
  3. use App\Validator\ValidationGroupResolver;
  4. use Symfony\Component\Form\AbstractType;
  5. use Symfony\Component\OptionsResolver\OptionsResolver;
  6. class MyClassType extends AbstractType
  7. {
  8. private $groupResolver;
  9. public function __construct(ValidationGroupResolver $groupResolver)
  10. {
  11. $this->groupResolver = $groupResolver;
  12. }
  13. // ...
  14. public function configureOptions(OptionsResolver $resolver): void
  15. {
  16. $resolver->setDefaults([
  17. 'validation_groups' => $this->groupResolver,
  18. ]);
  19. }
  20. }

This will result in the form validator invoking your group resolver to set the validation groups returned when validating.

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