如何在 Symfony 中允许使用 Assert/Type 和 null?

How to use Assert/Type with null allowed in Symfony?

是否可以验证实体的 属性 具有确切类型或空值? 换句话说,属性 可以具有精确类型的 optinal 值。

例如属性$date可以设置(\Datetime类型)也可以不设置:

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

不要介意@ORM\Column部分的nullable=true,它仅适用于数据库级别,不适用于模型验证。

问题是:如果 $date 不存在,错误是:

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

尝试使用 @Assert\DateTime() 代替:

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

Type 强制字段为指定类型的实例,而其他约束验证值是否为空(NotNull 等除外)。

请记住 @Assert\DateTime() 也接受正确的日期时间 string。但是您可以使用适当的 setter 来处理它,以强制此值为 null 或 \DateTime.