php - 如果验证失败则不更新实体 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上的一个线程没有得到最终结果。我真的需要有关如何正确防止实体更新并获得正确错误的帮助。
解决方案
'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())
}
推荐阅读
- node.js - 数据库上的firebase once('value')函数没有响应
- javascript - 如何为使用箭头函数的类方法的参数生成 jsdoc?
- docker - 当用户 linux docker image 没有问题,但 windows docker image 失败
- php - 仅用破折号替换被空格包围的连字符
- xml - 无法从 XSD 文件生成 XML
- wso2 - WSO2 API 构建和部署
- java - 如何在springboot中从其他集合中获取数据
- python - 如何使用 Flask REST API 存储 Excel 文件
- c# - 如何在 C# 中使用 foreach 从 XMLElement 中迭代数据
- azure - 有没有办法使用 AKS(Azure Kubernetes 服务)管理部署在 iotedge 设备上的模块?