SymfonyWorld Online 2021 Winter Edition December 9 – 10, 2021 100% Online 25 talks and 10 workshops

New in Symfony 4.1: Added support for immutable dates in forms

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

Contributed by
Valentin Udaltsov
in #25582.

The DateTimeImmutable class was introduced in PHP 5.5. It provides the same API as DateTime, but when calling to its modify() or set*() methods, it returns a new DateTimeImmutable object to not change the original value.

In recent Symfony versions we added support for immutable dates in several parts of the framework. In Symfony 4.1 we finished a long-standing petition from the community to add support for immutable dates in Symfony Forms.

When building a form with a DateTimeType, DateType or TimeType field, set their input options to the new datetime_immutable value:

use Symfony\Component\Form\Extension\Core\Type\DateTimeType;

$builder->add('startsAt', DateTimeType::class, array(
    'input' => 'datetime_immutable',

Now you can set a DateTimeImmutable object as the value of this field and when the form is submitted and valid, you'll get a DateTimeImmutable object back with the new value set by the user.

Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

New in Symfony 4.1: Added support for immutable dates in forms

Tweet this


Thank you ! This is a great improvement :-)
I like the immutable dates.

But was it not better to create a DateTimeImmutableType instead of a primitive (the string) switch?
Or even better a 'immutable' => bool, as option to support immutable DTO's and other things too? (no input_immutable since the input and output are both immutable).
It would even be better if PHP changed the DateTimeImmutable to implement Immutable which does not allow to change properties. And then use the interface as a trigger instead of configuration :P
A new value in the 'input' option is a way better than a new 'immutable' option or new Type because 'input' option indicates the type of underlying data in model object along with 'string', 'datetime', etc.
So 'datetime_immutable' in 'input' option is a coherent solution.
Created a polyfill bundle for those who want to use this feature with Symfony >=2.8

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.