Alexander
Alexander

Reputation: 387

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

Upvotes: 9

Views: 6624

Answers (1)

Jakub Matczak
Jakub Matczak

Reputation: 15656

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.

Upvotes: 4

Related Questions