|
| 1 | +How to dynamically configure validation groups |
| 2 | +============================================= |
| 3 | + |
| 4 | +If you need some advanced logic to determine the validation groups that cannot |
| 5 | +be simply determined by a simple callback (for example that requires a few |
| 6 | +services) you can use a service. Implement a service that implements ``__invoke`` |
| 7 | +which accepts a FormInterface as a parameter. |
| 8 | + |
| 9 | +.. code-block:: php |
| 10 | +
|
| 11 | + use Symfony\Component\Form\FormInterface; |
| 12 | + |
| 13 | + class ValidationGroupResolver |
| 14 | + { |
| 15 | + private $service1; |
| 16 | + private $sevice2; |
| 17 | + public function __construct($service1,$service2) |
| 18 | + { |
| 19 | + $this->service1 = $service1; |
| 20 | + $this->service2 = $service2; |
| 21 | + } |
| 22 | + |
| 23 | + public function __invoke(FormInterface $form) |
| 24 | + { |
| 25 | + //figure out what groups to apply and return an array |
| 26 | + } |
| 27 | + } |
| 28 | +
|
| 29 | +Then in your form, inject the resolver and set it as the ``validation_groups``. |
| 30 | + |
| 31 | +.. code-block:: php |
| 32 | +
|
| 33 | + use Symfony\Component\OptionsResolver\OptionsResolver; |
| 34 | + use Symfony\Component\Form\AbstractType |
| 35 | + |
| 36 | + class MyClassType extends AbstractType |
| 37 | + { |
| 38 | + private $groupResolver; |
| 39 | + public function __construct($groupResolver) |
| 40 | + { |
| 41 | + $this->groupResolver = $groupResolver; |
| 42 | + } |
| 43 | + |
| 44 | + // ... |
| 45 | + public function configureOptions(OptionsResolver $resolver) |
| 46 | + { |
| 47 | + $resolver->setDefaults(array( |
| 48 | + 'validation_groups' => $this->groupResolver, |
| 49 | + )); |
| 50 | + } |
| 51 | +
|
| 52 | +This will result in the form validator invoking your group resolver to |
| 53 | +set the validation groups returned when validating. |
| 54 | + |
| 55 | + |
0 commit comments