|
| 1 | +How to Dynamically Configure Validation Groups |
| 2 | +============================================== |
| 3 | + |
| 4 | +Sometimes you need advanced logic to determine the validation groups. If this |
| 5 | +can't be determined by a simple callback, you can use a service. Create a |
| 6 | +service that implements ``__invoke`` which accepts a ``FormInterface`` as a |
| 7 | +parameter. |
| 8 | + |
| 9 | +.. code-block:: php |
| 10 | +
|
| 11 | + namespace AppBundle\Validation; |
| 12 | +
|
| 13 | + use Symfony\Component\Form\FormInterface; |
| 14 | + |
| 15 | + class ValidationGroupResolver |
| 16 | + { |
| 17 | + private $service1; |
| 18 | +
|
| 19 | + private $service2; |
| 20 | +
|
| 21 | + public function __construct($service1, $service2) |
| 22 | + { |
| 23 | + $this->service1 = $service1; |
| 24 | + $this->service2 = $service2; |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * @param FormInterface $form |
| 29 | + * @return array |
| 30 | + */ |
| 31 | + public function __invoke(FormInterface $form) |
| 32 | + { |
| 33 | + $groups = array(); |
| 34 | +
|
| 35 | + // determine which groups to apply and return an array |
| 36 | +
|
| 37 | + return $groups; |
| 38 | + } |
| 39 | + } |
| 40 | +
|
| 41 | +Then in your form, inject the resolver and set it as the ``validation_groups``. |
| 42 | + |
| 43 | +.. code-block:: php |
| 44 | +
|
| 45 | + use Symfony\Component\OptionsResolver\OptionsResolverInterface; |
| 46 | + use Symfony\Component\Form\AbstractType |
| 47 | + use AppBundle\Validator\ValidationGroupResolver; |
| 48 | +
|
| 49 | + class MyClassType extends AbstractType |
| 50 | + { |
| 51 | + /** |
| 52 | + * ValidationGroupResolver |
| 53 | + */ |
| 54 | + private $groupResolver; |
| 55 | +
|
| 56 | + public function __construct(ValidationGroupResolver $groupResolver) |
| 57 | + { |
| 58 | + $this->groupResolver = $groupResolver; |
| 59 | + } |
| 60 | + |
| 61 | + // ... |
| 62 | + public function setDefaultOptions(OptionsResolverInterface $resolver) |
| 63 | + { |
| 64 | + $resolver->setDefaults(array( |
| 65 | + 'validation_groups' => $this->groupResolver, |
| 66 | + )); |
| 67 | + } |
| 68 | +
|
| 69 | +This will result in the form validator invoking your group resolver to |
| 70 | +set the validation groups returned when validating. |
0 commit comments