Symfony 8.2 New Published on

A collection of blocks of several kinds

PolymorphicCollectionType gives each entry of a collection the form of its kind: titles, paragraphs and quotes in the same page.

Topics covered: Forms

New in Symfony 8.2 (in development). A CollectionType has only one entry_type: all its entries go through the same form. For a page made of titles, paragraphs and quotes, you needed a catch-all form, with every field of every kind, or one collection per kind.

PolymorphicCollectionType

The new collection maps a name to each entry type, and a provider picks which one to apply to each entry:

$builder->add('blocks', PolymorphicCollectionType::class, [
    'entry_types' => [
        'title' => TitreType::class,
        'paragraph' => ParagrapheType::class,
    ],
    'entry_type_provider' => new BlocTypeProvider(),
    'allow_add' => true,
]);

The provider implements EntryTypeProviderInterface, and returns one of the names of entry_types:

  • forModelData() for an existing entry, from the object;
  • forSubmittedData() for an entry added by the browser, from the submitted array. An entry added in JavaScript has no object yet: its data must say what kind it is, for example through a hidden field.

With allow_add, the collection renders one prototype per kind, in the data-prototype-title, data-prototype-paragraph… attributes: the JavaScript picks which one to insert. entry_options, prototype_options and prototype_data are also given per kind name.

Your task

The “About” page mixes a title, a paragraph and a quote. PageType sends them all through ParagrapheType, and the form crashes as soon as it is displayed.

  1. Give each block the form of its kind: TitreType, ParagrapheType or CitationType, already written. Name the kinds title, paragraph and quote: those are the values of the hidden type field of these forms.
  2. Write BlocTypeProvider, for existing blocks as well as those added in the browser.

Where the feature comes from: the original pull request.