php - Symfony form date range plus existing date
问题描述
I have a form which I use for creating and updating an entity. One of the attributes is a date, startDate
, which input allows this year and next year. So currently, 2019 and 2020. This is my code in TestType.php:
->add('startDate', DateType::class, [
'years' => range(date('Y'), date('Y') +1),
])
This works as expected. There is one problem I face when a user wants to update an entity with a data with a year from the past, for example 2017
. What I would like in that case is to change the range to that year (2017) until now + 1 year (2020). Is there any way this can be achieved in the TestType.php file?
解决方案
您可以在预设数据事件上设置开始年份,例如:
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$event->getForm()->add('startDate', DateType::class, [
'years' => range(
$event->getData()->getStartDate() ?
$event->getData()->getStartDate()->format('Y') :
date('Y'),
date('Y')+1
),
]);
});
推荐阅读
- php - Laravel,从表中获取特定列的数据并将其存储在另一个表中的不同列名中
- c# - 在 If 语句中声明 Var
- shell - 如何从 shell 脚本调用 cmake 方法?
- bash - BASH,带有三个条件的 if 语句
- node.js - Firebase Auth 错误:您的 API 密钥无效,请检查您是否正确复制了它
- docker - 使用 conda install 构建 Docker 映像
- swift - 在 Swift 中使用转义函数来允许使用参数
- pysimplegui - PySimpleGUI - 窗口被初始化事件
- javascript - 这个字符串作为函数参数是如何工作的(没有括号?!)?
- kubernetes - 无法拉取镜像仓库不存在或可能需要“docker login”: