Symfony2 DateTime null accept Symfony2 DateTime null accept symfony symfony

Symfony2 DateTime null accept


In this case, the problem was caused by PHP type hinting.If you use type hinting (for instance setBirthDate(\DateTime $value)) then PHP forces you that you actually provide a DateTime object. Obviously, null is not such an object. To resolve this problem, it is possible to give $value a default value like this: setBirthDate(\DateTime $value = null).

This is documented behavior and explained in the PHP Documentation (http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration).

Relevant passage:

To specify a type declaration, the type name should be added before the parameter name. The declaration can be made to accept NULL values if the default value of the parameter is set to NULL.


The problem occurs due type-hinted setter as it is mentioned in the comments. There are two solutions:

1. Use 'by_reference' => true on your form:

$builder->add(    'birthDate',    DateType::class,    [        'widget' => 'single_text',        'format' => 'yyyy-MM-dd',        'by_reference' => true,    ]);

2. Let your setter accept null:

public function setBirthDate(\DateTime $value = null){   .....}


Don't pass any values to it. Make the field not required by doing this:

->add(    'birthDate',     DateType::class,     array(        'required' => false,        'widget' => 'single_text',        'format' => 'yyyy-MM-dd'    ))