首页 > 解决方案 > 如果验证失败则不更新实体 Symfony [form]

问题描述

使用 Symfony 3.4,当输入字段与正则表达式不匹配时,我不想更新并得到正确的错误。

这是我在实体中的电话字段

     /**
     * @var string
     *
     * @ORM\Column(name="phone", type="string", length=20, unique=true, nullable=false)
     * @Assert\NotBlank(message="Phone is required.")
     * @Assert\Regex(
     *      pattern=Presenter::PHONE_REGEX,
     *      message="Not a valid phone number"
     * )
     */
    private $phone;

我试图在$phone内部设置时捕获错误,setPhone($phone)如下所示

    /**
     * Set phone
     *
     * @param string $phone
     *
     * @return Worker
     */
    public function setPhone($phone)
    {
        if (preg_match(Presenter::PHONE_REGEX, $phone))
            $this->phone = $phone;
        return $this;
    }

而且我收到“需要电话”消息而不是“不是有效的电话号码”(因为在 WorkerType 中需要电话)。

我搜索了谷歌,发现github上的一个线程没有得到最终结果。我真的需要有关如何正确防止实体更新并获得正确错误的帮助。

标签: phpdoctrinesymfony-3.4

解决方案


'mapped' => false通过 PRE_SUBMIT 事件在 WorkerType for phone 字段中添加参数。

$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
      $phoneAttrs = [
          'mapped' => false,
          // add other attrs
      ];
      $event->getForm()->add('phone', TextType::class, phoneAttrs);
}

如果字段有效,则表单提交后手动调用 setPhone:

if ($form->get('phone')->isValid() {
    $entity->setPhone($form->get('phone')->getData())
}

推荐阅读