Symfony 8.2 New Published on

A form that reads PHP types

->add('seats') is enough: Symfony 8.2 infers the field type and its empty_data from the property's type, and an empty field no longer causes a TypeError.

Topics covered: Forms

New in Symfony 8.2 (in development). Symfony could already guess a field's type from validation constraints or from the Doctrine mapping. It now also reads the property's PHP type: ->add('seats') on a public int $seats gives an IntegerType, without writing anything more.

Property type Guessed field
int IntegerType
float NumberType
bool CheckboxType
DateTime, DateTimeImmutable, DatePoint DateTimeType (with the right input)
DateInterval DateIntervalType
string left to the default, TextType

The real gain: empty_data

A field sent empty writes null into the property. On a public string $title, that's a TypeError, so a 500 page, before NotBlank even had a chance to say “Give the event a title”. You had to remember 'empty_data' => '' on every field.

When the type is guessed, Symfony 8.2 also guesses empty_data from the type of the property (or of the setter):

public string $title = '';       // empty: ''
public int $seats = 0;           // empty: 0
public ?string $description;     // empty: null

Careful: nothing is guessed for a field whose type you write, such as ->add('title', TextType::class). And 0 passes NotBlank: to reject an empty number, make the property nullable.

Your task

EvenementType writes the type of every field. Submit the form with an empty title: the page crashes.

  1. Let Symfony guess the type of the title, the seats, “full” and the start.
  2. Keep the description's text area: the ?string type doesn't say a text is long.

Where the feature comes from: the original pull request.