简体   繁体   中英

Set default value for date in Sonata

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM