2017-06-23 26 views
2

是否可以使用確切類型或空值驗證實體的屬性? 換句話說,屬性可以有optinal確切類型的值。如何使用Symfony中允許空的Assert/Type?

例如,屬性$日可設置(\Datetime型)或不:

/** 
* @ORM\Column(type="datetime", nullable=true) 
* @Assert\Type("\DateTime") 
*/ 
protected $date; 

不要在@ORM\Column節介意nullable=true,它僅適用於DB-水平,而不是模型驗證。

的問題是:如果$日期不存在,錯誤的是:

Expected argument of type "DateTime", "NULL" given

+0

如何像'function setDate(\ DateTime $ date = null){'? –

+0

當你添加['IsNull'](https://symfony.com/doc/current/reference/constraints/IsNull.html)或['Blank'](https://symfony.com/doc/)時會發生什麼?電流/參考/約束/ Blank.html)。 –

回答

0

@Assert\DateTime()嘗試,而不是:

/** 
* @ORM\Column(type="datetime", nullable=true) 
* @Assert\DateTime() 
*/ 
protected $date; 

Type力量字段設置爲指定類型的實例而其他約束條件如果不爲空則驗證值(除了NotNull等)。

請記住,@Assert\DateTime()也接受正確的日期時間字符串。但是你可以用適當的setter來處理它,以強制這個值爲null或\DateTime

相關問題