Symfony 3.4-子类型中的验证组

时间:2018-09-28 20:08:11

标签: php symfony

我有两个模型和两种表单类型:

class User
{
    private $name;

    /**
     * @Assert\Valid()
     */
    private $address;
}

-

class Address
{
    /**
     * @Assert\NotBlank(groups={"street"})
     */
    private $street;

    /**
     * @Assert\NotBlank(groups={"number"})
     */
    private $number;
}

表单类型:

class AddressType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('street', TextType::class, [
                'required' => false
            ])
            ->add('number', IntegerType::class, [
                'required' => false
            ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Address::class,
            'validation_groups' => ['number']
        ]);
    }
}

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class, [
                'required' => false
            ])
            ->add('address', AddressType::class)
            ->add('submit', SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class
        ]);
    }
}

但是验证不起作用(对于AddressType中的字段编号)。此外,当我在表单类型定义中添加约束时:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class, [
                'required' => false
            ])
            ->add('address', AddressType::class, [
                'constraints' => [
                    new Valid()
                ]
            ])
            ->add('submit', SubmitType::class);
    }

验证开始工作。这对我来说很奇怪,我也不知道为什么。也许我的方法不好? UserType中的注释和配置有何区别?

0 个答案:

没有答案