So, I want to be able send a null option to my DOB field.
Here is my form builder:
->add('birthDate', DateType::class, array(
'widget' => 'single_text',
'format' => 'yyyy-MM-dd'))
And here is those field in my entity
/**
* @ORM\Column(
* type="date",
* nullable=true
* )
* @JMS\Groups("single")
*
* @var \DateTime
*/
protected $birthDate;
When I`m trying to send a null I got an error msg
Expected argument of type "DateTime", "NULL" given
any ideas?
CRITICAL - Uncaught PHP Exception Symfony\Component\PropertyAccess\Exception\InvalidArgumentException: "Expected argument of type "DateTime", "NULL" given" at /var/www/server.local/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php line 253
$type = $trace[$i]['args'][0];
$type = is_object($type) ? get_class($type) : gettype($type);
throw new InvalidArgumentException(sprintf('Expected argument of type "%s", "%s" given', substr($message, $pos, strpos($message, ',', $pos) - $pos), $type));
}
}
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'
)
)
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)
{
.....
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With