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.
- Give each block the form of its kind:
TitreType,ParagrapheTypeorCitationType, already written. Name the kindstitle,paragraphandquote: those are the values of the hiddentypefield of these forms. - Write
BlocTypeProvider, for existing blocks as well as those added in the browser.