子实体内的Symfony 3验证组被忽略

时间:2016-09-28 22:03:24

标签: php forms symfony

我有一个简单的表单,有两个字段,电子邮件和名称。电子邮件位于帐户实体和子实体中的名称:MedicalCenters

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;

class AccountsMedicalCentersType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email')
            ->add('name', TextType::class, array(
                'mapped' => false
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            array(
                'validation_groups' => array('emailValidation','Default')
                )
        );
    }
}

我想验证具有验证组的字段,因为在MedicalCenters实体中,我还有其他一些验证,其他情况:

帐户实体,验证工作正常:

/**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=100, nullable=true, unique=true)
     * @Assert\NotBlank(groups={"emailValidation"})
     * @Assert\Email(groups={"emailValidation"})
     *
     */
    protected $email;
 /**
     * @var \MedicalCenters
     *
     * @ORM\ManyToOne(targetEntity="MedicalCenters")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="medical_centers_id", referencedColumnName="id")
     * })
     *
     * @Assert\Valid
     *
     */
    private $medicalCenters;

MedicalCenters实体,验证组被忽略,返回的错误是第二个(地址不是空白):

/**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=300, nullable=true)
     * @Assert\NotBlank(message="name not blank", groups={"emailValidation"})
     *
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="address", type="text", length=65535, nullable=true)
     * @Assert\NotBlank(message="address not blank")
     */
    private $address;

我不明白为什么从子实体不仅仅验证名称字段,属于组emailValidation? 我做错了什么?

在控制器中我有:

$form = $this->createForm(
                AccountsMedicalCentersType::class,
                $currentAccount,
                array(
                    'validation_groups' => array(
                        'emailValidation',
                        'Default'
                    )
                )
            );

由于

1 个答案:

答案 0 :(得分:1)

添加选项cascade_validation可以解决问题,但不推荐使用该选项。使用Valid约束来验证子对象。来自Symfony文档:

  

此约束用于对作为要验证的对象的属性嵌入的对象启用验证。这允许您验证对象以及与之关联的所有子对象。 (来源:https://symfony.com/doc/current/reference/constraints/Valid.html

class AccountsMedicalCentersType extends AbstractType
{
    ....

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'validation_groups' => array('emailValidation','Default')
            'constraints' => array(
                new Valid()
            )
        ));
    }
}