【发布时间】:2021-04-09 04:48:03
【问题描述】:
使用 Symfony 5.1 和 Api 平台,我无法有效地处理保存 NULL 数据。
这个简单实体的例子:
class Foo
{
/**
* @var string
*
* @ORM\Column(type="string")
* @Assert\NotBlank()
*/
public $name;
/**
* @var string
*
* @ORM\Column(type="text", nullable=true)
*/
public $content;
}
示例 1(POST 请求):
{
"name": "",
"content": ""
}
我同意,这是很好的回报(ConstraintViolationList):
{
"@context": "/api/contexts/ConstraintViolationList",
...
"violations": [
{
"propertyPath": "name",
"message": "This value should not be blank."
}
]
}
示例 2(POST 请求):
{
"name": "test",
"content": ""
}
数据库中的注册进展顺利。在数据库中,对于content 值,我有""。 但我想保存NULL。
所以我知道 Api Platform 不知道如何将空数据 ("") 转换为 NULL 数据,就像 Symfony 在提交空表单后所做的那样。
所以我再次尝试示例 1,但使用 NULL 数据,以确保 Asserts 仍然有效。
{
"name": null,
"content": null
}
不行,我没有ConstraintViolationList错误:
{
"@context": "/api/contexts/Error",
...
"hydra:description": "The type of the "name" attribute must be "string", "NULL" given.",
}
那么我该如何处理空数据,如果它是空的并且是强制性的,我有一个错误列表(ConstraintViolationList),但如果它是可选的,那么数据注册为NULL 而没有""?
不得不根据数据是否是强制性的(有时发送"",有时发送NULL)以不同方式管理数据发送,这将是一种耻辱,非常非常乏味。
【问题讨论】:
-
你试过
@Assert\NotBlank(allowNull=true)吗?另外:正如 rugolinifr 在他的回答中指出的那样:您必须允许属性为null,因此请确保您的 getter/setter 支持它。它说“违反约束”的事实意味着您当前询问的问题与您的@Assert约束有关。 -
P.s -
NotBlank验证器表示字符串属性的值可能不是''。当您发送"name": null而不发送allowNull=true时,需要一个非空字符串,因此您的约束违规。 与allowNull=true表示该值可能是null或必须包含字符串字符(但仍可能不是''(空))。
标签: php symfony api-platform.com symfony-validator