简体   繁体   English

在奏鸣曲中设置日期的默认值

[英]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:我有一个日期,我想将当前日期设置为默认值,大多数帖子都建议添加'data' => new \DateTime()但在 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 . data属性将在所有情况下覆盖数据,您可以在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?您可以做的是在实体中设置默认值,而不是按照什么是设置 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.这样做的缺点是,当实体在 Sonata 之外创建时,它还会添加默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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