Symfony 4 was released on November 30th.
Update now to the best Symfony ever!

You are browsing the Symfony 4 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4 yet, browse the Symfony 3.4 documentation.

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 simple callback, you can use a service. Create a service that implements __invoke() which accepts a FormInterface as a parameter.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/Validation/ValidationGroupResolver.php
namespace App\Validation;

use Symfony\Component\Form\FormInterface;

class ValidationGroupResolver
{
    private $service1;

    private $service2;

    public function __construct($service1, $service2)
    {
        $this->service1 = $service1;
        $this->service2 = $service2;
    }

    /**
     * @param FormInterface $form
     * @return array
     */
    public function __invoke(FormInterface $form)
    {
        $groups = array();

        // ... determine which groups to apply and return an array

        return $groups;
    }
}

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/Form/MyClassType.php;
namespace App\Form;

use App\Validator\ValidationGroupResolver;
use Symfony\Component\Form\AbstractType
use Symfony\Component\OptionsResolver\OptionsResolver;

class MyClassType extends AbstractType
{
    private $groupResolver;

    public function __construct(ValidationGroupResolver $groupResolver)
    {
        $this->groupResolver = $groupResolver;
    }

    // ...
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'validation_groups' => $this->groupResolver,
        ));
    }
}

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.