symfony - 如何正确地将日期转换为字符串并以 symfony 形式返回,以便可以使用日期选择器
问题描述
在我的 Symfony 4 应用程序中,我有一个包含日期类型字段的实体。默认情况下,Symfony 将其显示为一组用于月、日、年的选择框。我已将其更改为文本小部件,以便可以使用 jQuery UI 日期选择器。
但是我在尝试提交表单时遇到了问题。
这是我实体上的字段:
/**
* @ORM\Column(type="date")
*/
private $start_date;
这是我显示该字段的方式:
$builder->add('start_date', DateType::class, [
'widget' => 'single_text',
// prevents rendering it as type="date", to avoid HTML5 date pickers
'html5' => false,
// adds a class that can be selected in JavaScript
'attr' => ['class' => 'js-datepicker'],
])
在我的页面上使用 jquery 和 jqueryui,这允许显示日期选择器。
这是我目前正在尝试从日期转换为字符串的方式,反之亦然。目前,我只是想使用一个硬编码的日期,一旦我知道我在做什么,我当然会改变它。
$builder->get('start_date')
->addModelTransformer(new CallbackTransformer(
function ( $dateAsString ) {
return new \DateTime('2019-01-01');
},
function ( $dateAsDate ) {
return '2019-01-01';
}
));
提交表单会产生此错误:“DateTimeInterface”类型的预期参数,“字符串”给定。
有没有人知道如何将日期作为日期类型存储在我的实体中,同时在我的表单中将其显示为字符串?
解决方案
I invite you to check out the documentation of DateType
. You will find out that you can store your date in variety of formats depending on input
option :
- string (e.g. 2011-06-05)
- datetime (a DateTime object)
- datetime_immutable (a DateTimeImmutable object)
- array (e.g. ['year' => 2011, 'month' => 06, 'day' => 05])
- timestamp (e.g. 1307232000)
This is an underlying model value
in your entity. In your example you must chose datetime
which is the default.
You made a right choise for widget
option - single_text
. Don't forget to set a right format
. This is view value
.
In your case you don't need to write your own data transformer. Symfony will take care of transforming your model value
in view value
and vice versa. It makes it using via normalised value
:
`model data`(string, datetime, timestamp, etc.) -> `norm data` (`DateTime`) -> `view data` (string for widget=single_text, array for widget=choice)
and
`view data` (string for widget=single_text, array for widget=choice) -> `norm data` (`DateTime`) -> `model data`(string, datetime, timestamp, etc.)
While the formats of view data
and model data
vary, the format of norm data
is always the same - DateTime
. The model transformer you added returned string
to be set to normalized data. That's why you got an error.
推荐阅读
- java - 不兼容的类型:int[] 无法转换为 int [in __Driver__.java]
- algolia - 记录加入可能吗?
- flutter - 如何添加创建新容器的搜索栏-Flutter
- python - 循环内的调用函数在python中不起作用
- django - Django为所有相关子项添加子行
- javascript - 如何在图表 Js 中隐藏点标签?
- swift - 无法将“Int”类型的值转换为预期的参数类型“Range”
- javascript - 如何在 react-select 自动下拉菜单中使用 react-simple-keyboard
- scala - 如何修复在akka scala中产生持久演员时的断路器超时异常?
- google-sheets - 如何提取谷歌表格中引号内的文本?