在另一个字段上执行NotBlank验证操作

时间:2019-06-17 07:40:04

标签: symfony

我有一个symfony表单,只有在@Assert\NotBlank(如果不为空白)时才需要触发$receiverNewsletter

/**
 * @var string
 *
 * @Assert\NotBlank
 * @Assert\Email
 *
 * @ORM\Column(name="email", type="string", length=190)
 */
private $email;


/**
 * @var bool
 *
 * @ORM\Column(name="receiveNewsletter", type="boolean")
 */
private $receiveNewsletter;

我的表单的一部分:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('receiveNewsletter', CheckboxType::class, ['label' => 'form.label.receiveNewsletter'])
            ->add('email', EmailType::class, ['label' => 'form.label.email', 'required' => false])
}

有什么想法如何使用有效负载来表示receiveNewsletter是否不为null,然后在电子邮件字段上触发NotBlank验证吗?

1 个答案:

答案 0 :(得分:2)

您可以将Expression约束用于此特定功能。它没有专门使用NotBlank,但我发现它是更优雅的解决方案。

use Symfony\Component\Validator\Constraints as Assert;

/**
 * @Assert\Expression(
 *     "(this.getReceiveNewsletter() and this.getEmail()) or !this.getReceiveNewsletter()",
 *     message="Email cannot be empty when Receive Newsletter is marked"
 * )
 */
class Entity
{
...
}

您对整个实体施加了约束,它根据expression syntax计算表达式。