Symfony DateTimeType 没有秒/当天的 TimeType [英] Symfony DateTimeType without seconds / TimeType for current day
问题描述
对于我的项目,我需要多个具有特殊"配置的 DateTimeType - 但我根本不知道如何实现这些目标(Symfony 5).
For my project I need multiple DateTimeTypes with "special" configuration - but I simply have no idea how to achieve those things (Symfony 5).
1.没有秒的 DateTimeType(但仍然是 HTML5)
$builder
->add('arrival', DateTimeType::class, ['label' => 'Arrival', 'input' => 'datetime_immutable', 'widget' => 'single_text']);
这会呈现一个类型为 datetime-local
的 HTML5 输入字段,这正是我想要的 - 除了它还有几秒钟:
This renders a HTML5 input field with type datetime-local
which is exactly what I want - except it still has seconds:
我希望删除 :46.这显然来自 symfony 自动(?)设置的 value 选项:
I want the :46 removed. This clearly comes from the value option which is automatically(?) set by symfony:
从技术上讲,这已经适用于 chrome 等.但是由于秒数,这在 Safari 中无法通过客户端验证.
Technically this already works in chrome etc. However this fails the client-side validation in Safari because of the seconds.
如何去除秒数?format
选项不能使用(因为它需要将 html5 设置为 false)!
How can I remove the seconds? The format
option can not be used (because it requires html5 to be set to false)!
2.当天的时间类型
如果您将 TimeType 与 DateTime
对象一起使用,则日期将始终为 1970-01-01
,这完全有意义 - 但是您如何预先选择对象的日期(例如今天)并让用户选择时间?
If you use the TimeType with a DateTime
object, the date will always be 1970-01-01
which makes total sense - however how can you pre-select the date of the object (e.g. today) and let the user pick the time?
我怎样才能做到这一点?
推荐答案
为了设置今天的默认值,我在实体对象中使用了 construct
方法.
To set the default value for today, I am using the construct
method in my entity object.
public function __construct()
{
$this->arrival = new \DateTimeImmutable();
$this->departure = \new \DateTimeImmutable();
}
第一季度的答案:为了删除秒,只需创建一个没有秒的新 DateTime
对象.
Answer for Q1:
In order to remove the seconds, just create a new DateTime
object without the seconds.
public function __construct()
{
$this->arrival = \DateTimeImmutable::createFromFormat('Y-m-d H:i', date('Y-m-d H:i'));
$this->departure = \DateTimeImmutable::createFromFormat('Y-m-d H:i', date('Y-m-d H:i'));
}
//$this->arrival = new \DateTimeImmutable(date('Y-m-d H:i')); //this also works, but needs execption handling (try/catch)
Q2 的答案:此问题的答案相同 - 只需在实体中预先设置当前日期并使用 TimeType
让用户选择时间.
Answer for Q2: Same answer for this question - just pre-set the current date in the entity and use the TimeType
to let the user pick the time.
这篇关于Symfony DateTimeType 没有秒/当天的 TimeType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!