Symfony 8.2 New Published on

A form for an immutable object

Symfony 8.2 calls the constructor of a readonly class: no more intermediate array or copied constraints, but a new object to read from getData().

Topics covered: FormsDTO

New in Symfony 8.2 (in development). A form writes its data into the object through its setters or public properties. On a readonly class, that was impossible: you went through an array, then rebuilt the object by hand, or wrote an empty_data closure and a setter closure per field.

Since Symfony 8.2

When the constructor has required arguments or promoted readonly properties, the form calls the constructor with the data of its fields, matched by property name.

final readonly class Profil
{
    public function __construct(
        #[Assert\NotBlank]
        public string $name,
        public ?string $city = null,
    ) {
    }
}

The constructor's constraints are checked and reported on their field, as for any class.

Editing an existing object

An immutable object doesn't change: when a field mapped to a readonly property changes, Symfony returns a new object, with the other arguments copied from the original. The original stays intact, so the result must be read from the form:

$form = $this->createForm(ProfilType::class, $profile);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $profile = $form->getData(); // a new object if a field changed
}

Condition: the constructor must promote all the properties, so nothing is lost when the object is created again. An entity with a private $id, for example, isn't a good fit.

Your task

ProfilType works on an array: the controller copies the profile into it, then rebuilds a Profil by hand, and the type copies the class's constraints… except one, forgotten along the way.

  1. Put the form on Profil itself, without copied constraints.
  2. Save the edited profile.

Where the feature comes from: the original pull request.