2017-06-29 40 views
0

我有被暴露的API平台的资源实体,并包含以下属性:API平台 - 更新可为空字符串错误

/** 
* @ORM\Column(type="string", nullable=true) 
*/ 
private $note; 

当我尝试更新的实体(通过PUT)发送以下JSON:

{ 
    "note": null 
} 

我从Symfony的串行以下错误:

[2017年6月29日21时47分33秒]请求.CRITICAL:未捕获到的PHP异常Symfony \ Component \ Serializer \ Exception \ UnexpectedValueException:“在/ var/www/html/testapp/server/vendor/symfony/symfony/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php第196行{“exception”:“[object](Symfony \ Component \ Serializer \ Exception \ UnexpectedValueException(code:0):\”string \“,\” NULL“,在/var/www/html/testapp/server/vendor/symfony/symfony/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php:196,Symfony \ Component \ PropertyAccess \ Exception \ InvalidArgumentException(代码: 0):在/var/www/html/testapp/server/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php:275处给出的类型\“string \”,\“NULL \”的预期参数)“} []

这似乎是我错过了一些配置,以允许此属性上的空值?为了让事情变得怪异,当我得到一个包含空音符的资源,那么说明是正常返回NULL:

{ 
    "@context": "/contexts/RentPayment", 
    "@id": "/rent_payments/1", 
    "@type": "RentPayment", 
    "id": 1, 
    "note": null, 
    "date": "2016-03-01T00:00:00+00:00" 
} 

我缺少什么 - PS我是一个巨大的福利局到API平台

+1

只是一个狂野的刺,但你使用类型暗示二传手? –

+0

谢谢!呃,为什么我没有想到 - 如果你愿意,可以把它作为答案加进去。 – dblack

回答

1

好吧作为意见确定你使用的是类型暗示二传手点菜:

public function setNote(string $note) { 
    $this->note = $note; 
    return $this; 
} 

随着PHP 7.1的,我们有nullable types所以下面将是首选,因为它实际上检查null或字符串,而不是任何类型的。

public function setNote(?string $note) { 

在以前的版本中,只删除类型提示,如果喜欢在里面添加一些类型检查。

public function setNote($note) { 
    if ((null !== $note) && !is_string($note)) { 
     // throw some type exception! 
    } 

    $this->note = $note; 
    return $this; 
} 

你可能要考虑的另一件事是使用类似:

$this->note = $note ?: null; 

这是如果(ternary operator)的sorthand。如果字符串为空(但是'0'错误,所以你可能需要做更长的版本)将值设置为空。