Home > database >  Set default value for date in Sonata
Set default value for date in Sonata

Time:09-06

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:

  1. if I change the date to a random one or even leave it empty, it will still save in the database the current one
  2. in the edit view it will override the date from the create view and the value will still be the current date

My code:

$form->add('startDate', DateType::class, [
        'required' => false,
        'label' => 'Starting date',
        'data' => new \DateTime("now"),
        'constraints' => ...
   ])
]);

What am I missing?

CodePudding user response:

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.

  • Related