[英]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 中有两个问题:
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.