首页 > 解决方案 > 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?

标签: phpsymfony

解决方案


您可以在预设数据事件上设置开始年份,例如:

$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
         ),
    ]);
});

Symfony 的表单事件文档


推荐阅读