Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is it possible to validate the entity's property with exact type OR null? In other words, the property can have optinal value of exact type.

For example, property $date can be set (\Datetime type) or not :

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

Do not mind nullable=true in @ORM\Column section, it only applies to DB-level, not model validation.

The problem is: If $date not present, the error is:

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

like image 210
Alexander Avatar asked Jun 23 '17 12:06

Alexander


1 Answers

Try with @Assert\DateTime() instead:

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

Type forces field to be instance of specified type, while other constraints validates value if it's not null (except for NotNull etc).

Remember that @Assert\DateTime() also accepts correct datetime string. But you can handle it with proper setter to force this value to be either null or \DateTime.

like image 167
Jakub Matczak Avatar answered Nov 18 '22 08:11

Jakub Matczak