Skip to content

Commit f19b81a

Browse files
committed
Added callable validation_groups example
Recently I had a need to dynamically set the validation_groups of a small set of forms based on the user that was logged in. In digging about the FormValidator::resolveValidationGroups and saw I could use a class that implements the __invoke method. Figured I might as well write something about it and see if you'd want to add it to the docs.
1 parent 0fb7847 commit f19b81a

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

book/forms.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,11 @@ large or whether you tried to submit text in a number field.
621621

622622
.. _book-forms-type-reference:
623623

624+
.. seealso::
625+
626+
To see how to use a service with dependencies to resolve ``validation_groups``
627+
checkout cookbook article :doc:`/cookbook/validation/validation-groups-service-resolver`.
628+
624629
Built-in Field Types
625630
--------------------
626631

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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

Comments
 (0)