> Symfony中文手册 > 如何动态地配置验证组

如何动态地配置验证组

有时你需要先进的逻辑来决定验证组。如果他们不能被一个简单的回调决定,您可以使用一个服务。创建一个服务让它实现__invoke,并接受FormInterface作为参数。

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
31
// src/AppBundle/Validation/ValidationGroupResolver.PHP
namespace AppBundle\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;
    }
}

这时,在你的表单,注入这个解析器(resolver)并设置它作为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/AppBundle/Form/MyClassType.php;
namespace AppBundle\Form;
 
use AppBundle\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,
        ));
    }
}

当验证时,它将导致表单验证器( form validator )调用你的组解析器(group resolver),来设置返回的验证组。