Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 62 ยท Forms and Validation

Advanced Forms

Go beyond simple forms in Symfony with embedded forms, collections that add and remove rows, form events, data transformers and dependent dropdown fields.

Real forms are rarely a flat list of text boxes. An invoice has any number of line items. A user profile embeds an address. A tag field is a comma-separated string on screen but a list of objects in your model. A "state" dropdown depends on the country selected just above it. The Form component handles all of these with four tools: embedded forms, collections, data transformers and form events.

This lesson shows each tool and when to use it. Real Symfony code is read-only. The two runnable stand-ins model the ideas, a transformer pipeline and an event-driven dependent field, in plain PHP, so you can watch the data flow without a framework.

Embedded forms

A form type is reusable, so one form can use another as a field. Suppose a customer has an address that appears on several pages:

PHP
// src/Form/AddressType.php
class AddressType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('street', TextType::class)
            ->add('city', TextType::class)
            ->add('postalCode', TextType::class);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(['data_class' => Address::class]);
    }
}

// src/Form/CustomerType.php (excerpt)
$builder
    ->add('name', TextType::class)
    ->add('billingAddress', AddressType::class)
    ->add('shippingAddress', AddressType::class, ['required' => false]);

The embedded form reads and writes the Address object returned by getBillingAddress(). Field names nest (customer[billingAddress][street]) and Twig renders the group with form_row(form.billingAddress). If a validated property holds an object, remember that nested validation needs the Valid constraint on that property (see Validation). Embedded forms keep the pieces small, testable and reusable, instead of one huge form class.

Sometimes you want to reuse fields without nesting them in the submitted data. The inherit_data option makes a sub-form read from its parent's data class, which is handy when two entities share a group of fields (for example location fields on both Company and Event).

Collections

CollectionType renders a list of sub-forms, one for each element of an array or collection. This is the tool for invoice lines, phone numbers or tags:

PHP
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

$builder->add('items', CollectionType::class, [
    'entry_type' => InvoiceItemType::class,
    'entry_options' => ['label' => false],
    'allow_add' => true,
    'allow_delete' => true,
    'by_reference' => false,
    'delete_empty' => true,
]);

The options do the following:

Option Meaning
entry_type The form type used for each element
entry_options Options passed to each element's form
allow_add Accept submitted rows that do not exist yet, and render a prototype
allow_delete Remove an element when its row is missing from the submission
by_reference With false, Symfony calls addItem() and removeItem() instead of modifying the returned collection
delete_empty Drop rows that are submitted completely empty

For by_reference => false to work, your entity needs adder and remover methods, and in a Doctrine relation they must also keep the owning side in sync:

PHP
class Invoice
{
    /** @var Collection<int, InvoiceItem> */
    private Collection $items;

    public function __construct()
    {
        $this->items = new ArrayCollection();
    }

    public function getItems(): Collection
    {
        return $this->items;
    }

    public function addItem(InvoiceItem $item): static
    {
        if (!$this->items->contains($item)) {
            $this->items->add($item);
            $item->setInvoice($this);
        }
        return $this;
    }

    public function removeItem(InvoiceItem $item): static
    {
        if ($this->items->removeElement($item) && $item->getInvoice() === $this) {
            $item->setInvoice(null);
        }
        return $this;
    }
}

Without those methods (or with by_reference left at true), changes to the collection may never reach the owning side of the relation and nothing is saved. Removed rows also need orphanRemoval: true on the Doctrine mapping if you want the rows deleted from the database; relations are covered in Relations.

Adding rows in the browser

With allow_add, Symfony renders a prototype: a template for a new row in which the index is replaced by the placeholder __name__. You put it in a data- attribute and let a little JavaScript insert copies:

TWIG
<ul id="items" data-prototype="{{ form_widget(form.items.vars.prototype)|e('html_attr') }}"
    data-index="{{ form.items|length }}">
    {% for itemForm in form.items %}
        <li>{{ form_widget(itemForm) }}</li>
    {% endfor %}
</ul>
<button type="button" id="add-item">Add line</button>
JavaScript
document.getElementById('add-item').addEventListener('click', () => {
    const list = document.getElementById('items');
    const index = Number(list.dataset.index);
    const html = list.dataset.prototype.replace(/__name__/g, index);
    list.dataset.index = index + 1;
    list.insertAdjacentHTML('beforeend', '<li>' + html + '</li>');
});

Symfony UX also ships a ready-made Stimulus controller for this, so you do not have to write the script yourself. Remember: the server must never trust the number of rows or their contents. Validation runs on every row as usual, and you may want a Count constraint to limit how many rows are allowed.

Data transformers

A form field works with three versions of the same value:

flowchart LR
    M["Model data<br/>(array of tags)"] <-->|"model transformers"| N["Norm data<br/>(normalized value)"]
    N <-->|"view transformers"| V["View data<br/>(string in the text box)"]

Data flows from the model to the view when displaying and back when submitting; transformers convert between the stages.

The type you choose supplies the standard transformers (that is how DateType turns a DateTimeImmutable into the string 2030-02-28). A data transformer is your own conversion for a field. It implements two methods: transform() (model to view, for display) and reverseTransform() (view to model, on submission). The classic example is tags: your entity holds an array, and the user types php, symfony, forms:

PHP
use Symfony\Component\Form\CallbackTransformer;

$builder->add('tags', TextType::class, ['required' => false]);

$builder->get('tags')->addModelTransformer(new CallbackTransformer(
    fn (array $tagsAsArray): string => implode(', ', $tagsAsArray),
    fn (string $tagsAsString): array => array_values(array_filter(array_map('trim', explode(',', $tagsAsString)))),
));

For anything reusable or testable, write a class instead:

PHP
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

final class IssueToNumberTransformer implements DataTransformerInterface
{
    public function __construct(private IssueRepository $issues)
    {
    }

    public function transform(mixed $issue): string
    {
        return $issue === null ? '' : (string) $issue->getNumber();
    }

    public function reverseTransform(mixed $issueNumber): ?Issue
    {
        if (!$issueNumber) {
            return null;
        }
        $issue = $this->issues->findOneBy(['number' => $issueNumber]);
        if ($issue === null) {
            throw new TransformationFailedException(sprintf('Issue number "%s" does not exist.', $issueNumber));
        }
        return $issue;
    }
}

Throwing TransformationFailedException is how a transformer reports bad input: the form becomes invalid and the field shows the invalid_message option (or you can pass a custom message to the exception with setInvalidMessage()). Use addModelTransformer() to adapt your model to the field's normalized value and addViewTransformer() for the normalized-to-text stage; for most custom cases addModelTransformer() is the right one.

Also remember that not every conversion needs a transformer: if the field is a choice of entities, use EntityType (Form Types and Options); if it is an embedded object, use an embedded form.

The first stand-in builds the same pipeline: a field with model and view transformers, a failing transformer, and the three representations printed side by side.

PHP A data transformer pipeline (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The tag example normalizes spacing, drops empty entries and duplicates, and rejects unsafe characters before your model ever sees them. The issue example shows the other common use: turning a typed identifier into an object, with a clear failure when it does not exist.

Form events

A form goes through a fixed life cycle, and you can hook into it with event listeners. Events are how you change a form's structure while it is being built or submitted.

flowchart TD
    A["PRE_SET_DATA<br/>before the form gets its data"] --> B["POST_SET_DATA<br/>after data is set"]
    B --> C["(user submits)"]
    C --> D["PRE_SUBMIT<br/>raw submitted data, before it is processed"]
    D --> E["SUBMIT<br/>data converted to normalized form"]
    E --> F["POST_SUBMIT<br/>submission complete, data final"]

The five form events: two for populating the form, three for handling a submission.

Event Typical use
PRE_SET_DATA Add or remove fields depending on the object being edited (hide slug once it exists)
POST_SET_DATA Read the data after it has been mapped
PRE_SUBMIT Change the raw submitted data or add fields that depend on it (dependent dropdowns)
SUBMIT Change normalized data before it is mapped to the model
POST_SUBMIT React once everything is done (the data is final; you can no longer change it)

Listeners are attached in buildForm():

PHP
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event): void {
    $form = $event->getForm();
    $task = $event->getData();            // the Task object, or null for a new one

    if ($task !== null && $task->getId() !== null) {
        $form->add('done', CheckboxType::class, ['required' => false]);
    }
});

You can also write listeners as separate classes and subscribe to several events with EventSubscriberInterface, which keeps buildForm() readable when the logic grows.

Dependent fields

The most requested use of events is a field whose choices depend on another field. The state or province list depends on the country. The rule is: the form must be rebuilt in two situations, when it is first displayed with existing data, and when it is submitted, because the user may have changed the country and the submitted state must be checked against the new country's list.

PHP
private function addStateField(FormInterface $form, ?string $country): void
{
    $form->add('state', ChoiceType::class, [
        'choices' => $this->states->forCountry($country),   // [] when there is no country
        'placeholder' => 'Choose a state',
    ]);
}

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder->add('country', CountryType::class);

    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event): void {
        $this->addStateField($event->getForm(), $event->getData()?->getCountry());
    });

    $builder->get('country')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event): void {
        $this->addStateField($event->getForm()->getParent(), $event->getForm()->getData());
    });
}

The POST_SUBMIT listener is attached to the country child, not to the whole form, and it rebuilds state on the parent with the new country. (Attaching a PRE_SUBMIT listener to the parent and reading $event->getData()['country'] works too.) If you skip the second listener, a user who changes the country gets "This value is not valid" on a perfectly good state, because the form still holds the old list.

In the browser, you also need a way to refresh the dropdown without a full reload: submit the form with JavaScript when the country changes, render only the state field, and swap it in, or use a Symfony UX Live Component, which can re-render a form on each change and reuses your form type unchanged.

The second stand-in has a miniature form with events. It compares a form that only rebuilds the field on PRE_SET_DATA with one that also rebuilds it on submit.

PHP Dependent fields with form events (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The form that listens only to PRE_SET_DATA insists on the old US list and rejects a valid Canadian province, which is exactly the bug the second listener prevents. The rebuilt form still protects you: a state that is not in the chosen country's list is refused, so the dependent dropdown is a convenience and the server keeps checking.

When forms get too complicated

Advanced forms are powerful, and they are also where complexity piles up. A few habits keep them manageable:

  • Prefer small embedded types over one enormous class.
  • Move conversions into transformer classes that you can unit test.
  • When a form needs many dependent fields and live updates, consider a Live Component or a dedicated JavaScript widget instead of ever-longer event listeners.
  • Keep the data object simple. A DTO built for the form can differ from your entity, and mapping it onto the entity in a service is often clearer than forcing the entity to fit the form.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must an entity provide for by_reference => false on a CollectionType to work?

    With by_reference false, the form calls addItem() and removeItem() (and you keep the relation's owning side in sync inside them).
  2. 2. Which transformer method runs when the user submits the form?

    transform() converts model data to what the view shows; reverseTransform() converts the submitted view value back to model data.
  3. 3. How should a data transformer report an invalid submitted value?

    TransformationFailedException makes the form invalid and shows the field's invalid_message (or the message you set).
  4. 4. Why must the state list of a dependent dropdown also be rebuilt when the form is submitted?

    The user may change the country. If the form still holds the old choices, a valid new state is rejected as an invalid choice.
  5. 5. Which event is the right place to add a field that depends on the object being edited?

    PRE_SET_DATA runs before the form receives its data, so you can add or remove fields based on the object. Later events no longer shape the form's structure.

Summary

  • Embed one form type in another to reuse field groups; use inherit_data when two models share fields.
  • CollectionType handles lists of rows: set entry_type, allow_add, allow_delete and by_reference => false, give the entity adder and remover methods, and use the prototype with a little JavaScript to add rows.
  • Data transformers convert between model, normalized and view data: transform() for display, reverseTransform() for submission, and TransformationFailedException for bad input.
  • Form events (PRE_SET_DATA, POST_SET_DATA, PRE_SUBMIT, SUBMIT, POST_SUBMIT) let you change a form while it loads or submits; dependent fields must be rebuilt both on load and on submit.
  • Keep advanced forms understandable with small types, testable transformers and, when needed, DTOs or Live Components.

Next up: Validation.