Dirk J. Faber
Dirk J. Faber

Reputation: 4701

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?

Upvotes: 0

Views: 302

Answers (1)

G1.3
G1.3

Reputation: 1879

You can set the start year on pre set data event like:

$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's form events documentation

Upvotes: 2

Related Questions