Skip to content

Commit 0559274

Browse files
afurculitaxabbuh
authored andcommitted
Create validation_group_service_resolver.rst
1 parent b131a68 commit 0559274

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
How to Dynamically Configure Form Validation Groups
2+
==============================================
3+
4+
Sometimes you need advanced logic to determine the validation groups. If they
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+
// src/AppBundle/Validation/ValidationGroupResolver.php
12+
namespace AppBundle\Validation;
13+
14+
use Symfony\Component\Form\FormInterface;
15+
16+
class ValidationGroupResolver
17+
{
18+
private $service1;
19+
20+
private $service2;
21+
22+
public function __construct($service1, $service2)
23+
{
24+
$this->service1 = $service1;
25+
$this->service2 = $service2;
26+
}
27+
28+
/**
29+
* @param FormInterface $form
30+
* @return array
31+
*/
32+
public function __invoke(FormInterface $form)
33+
{
34+
$groups = array();
35+
36+
// ... determine which groups to apply and return an array
37+
38+
return $groups;
39+
}
40+
}
41+
42+
Then in your form, inject the resolver and set it as the ``validation_groups``.
43+
44+
.. code-block:: php
45+
46+
// src/AppBundle/Form/MyClassType.php;
47+
namespace AppBundle\Form;
48+
49+
use AppBundle\Validator\ValidationGroupResolver;
50+
use Symfony\Component\Form\AbstractType
51+
use Symfony\Component\OptionsResolver\OptionsResolver;
52+
53+
class MyClassType extends AbstractType
54+
{
55+
private $groupResolver;
56+
57+
public function __construct(ValidationGroupResolver $groupResolver)
58+
{
59+
$this->groupResolver = $groupResolver;
60+
}
61+
62+
// ...
63+
public function configureOptions(OptionsResolver $resolver)
64+
{
65+
$resolver->setDefaults(array(
66+
'validation_groups' => $this->groupResolver,
67+
));
68+
}
69+
}
70+
71+
This will result in the form validator invoking your group resolver to set the
72+
validation groups returned when validating.

0 commit comments

Comments
 (0)