I have a date that I'd like to set as the default value the current date and most of the posts suggest to add the 'data' => new \DateTime()
but there are two issues with that in Sonata:
My code:
$form->add('startDate', DateType::class, [
'required' => false,
'label' => 'Starting date',
'data' => new \DateTime("now"),
'constraints' => ...
])
]);
What am I missing?
The data
attribute will overwrite data in all cases, as you can read here in DateType Field#data.
What you can do is set a default value in the entity instead as described in What is the best way to set defaults values of a Symfony object?
In the entity, you would have the following:
private $startDate = new \DateTime("now");
The downside of this is that it also adds the default value when the entity is created outside of Sonata.