API平台错误,字段不能为空

时间:2020-01-08 13:34:51

标签: symfony symfony4 api-platform.com

我有一个简单的实体

 /**
 * @var string|null
 *
 * @ORM\Column(name="city", type="string", length=255, nullable=false)
 * @Assert\NotNull()
 */
private $city;

 ...

  /**
 * @param string|null $city
 * @return CustomerAddressList
 */
public function setCity(?string $city): CustomerAddressList
{
    $this->city = $city;
    return $this;
}

如果我尝试将null传递到字段city,则结果是运行时异常,而不是验证错误:

{
  "@context": "/api/v2/contexts/Error",
  "@type": "hydra:Error",
  "hydra:title": "An error occurred",
  "hydra:description": "The type of the address attribute must be string, NULL given."
}

如果我将nullable=false更改为true,则一切正常,但这不是可接受的解决方案。

我该如何解决?

1 个答案:

答案 0 :(得分:2)

找到了解决方案。

* @ApiResource(
*     denormalizationContext={"disable_type_enforcement"=false}
* )

denormalizationContext中添加"disable_type_enforcement"=false会禁用使用Doctrine注释的请求验证。

{
    "@context": "/api/v2/contexts/ConstraintViolationList",
    "@type": "ConstraintViolationList",
    "hydra:title": "An error occurred",
    "hydra:description": "city: This value should be not null",
    "violations": [
    {
    "propertyPath": ".city",
    "message": "This value should be not null."
},

如果必须将字段强制为特定类型,则必须添加适当的@Assert\Type(...)作为以前的Symfony 4.3