Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 62 ยท Forms and Validation

Forms - Building and Rendering

Build your first Symfony form with AbstractType and the form builder, handle the request in a controller, render it in Twig and style it with form themes.

HTML forms look simple until you build a real one. You must print each field with the right value, read the submitted data back, convert strings to numbers and dates, check the input, show errors next to the right field, protect against forged requests, and keep the user's input when something is wrong. Writing that by hand for every page is repetitive and easy to get wrong.

Symfony's Form component does the repetitive parts. You describe a form once, as a class, and Symfony renders it, maps submitted data onto an object, and works together with the validator to produce errors. This lesson covers the building blocks: the form class, the controller, rendering in Twig and themes. The next lessons add field types, submission and CSRF and advanced features. Real Symfony code is read-only here; the runnable examples are a plain-PHP stand-in that mimics the same flow.

The idea: describe, handle, render

Every Symfony form goes through the same three steps:

flowchart LR
    A["Form class<br/>(AbstractType)"] --> B["createForm()<br/>in the controller"]
    B --> C["handleRequest()<br/>reads POST data"]
    C --> D{"submitted<br/>and valid?"}
    D -->|"yes"| E["Use the data,<br/>then redirect"]
    D -->|"no"| F["Render the form<br/>with Twig"]

A form is described once, then handled and rendered by the controller; a successful submission ends in a redirect.

Install the component with Composer (a --webapp project usually has it already) and generate a first form class with the maker:

Terminal
composer require symfony/form symfony/validator
php bin/console make:form TaskType Task

A data class

A form maps its fields onto some data. The most common target is a plain object, here a small Task:

PHP
<?php
// src/Entity/Task.php  (or any class: a form does not need Doctrine)

namespace App\Entity;

class Task
{
    private string $title = '';
    private ?\DateTimeImmutable $dueDate = null;
    private bool $done = false;

    public function getTitle(): string { return $this->title; }
    public function setTitle(string $title): void { $this->title = $title; }

    public function getDueDate(): ?\DateTimeImmutable { return $this->dueDate; }
    public function setDueDate(?\DateTimeImmutable $dueDate): void { $this->dueDate = $dueDate; }

    public function isDone(): bool { return $this->done; }
    public function setDone(bool $done): void { $this->done = $done; }
}

The form reads and writes each field through the PropertyAccess component, which understands getters (getTitle(), isDone()) and setters (setTitle()), and also works with public properties. If you do not pass any object, the form simply uses an array.

The form class

A form type is a class that extends AbstractType. Its buildForm() method adds the fields, and configureOptions() sets the form's options. By convention, form classes live in src/Form/:

PHP
<?php
// src/Form/TaskType.php

namespace App\Form;

use App\Entity\Task;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('title', TextType::class, ['label' => 'What needs doing?'])
            ->add('dueDate', DateType::class, ['widget' => 'single_text', 'required' => false])
            ->add('done', CheckboxType::class, ['required' => false])
            ->add('save', SubmitType::class, ['label' => 'Save task']);
    }

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

Each add() call takes the field name (the property it maps to), the type and an array of options. The type decides the HTML (TextType renders <input type="text">, CheckboxType a checkbox) and how the submitted string is converted back to PHP. The data_class option tells the form which class to create when no object is given; it is the single most important option on a form for an object.

You can even omit the type: if data_class is set and the property has a known type or a validator constraint, Symfony can guess the field type when you write ->add('title'). Being explicit, as above, makes the form easier to read and does not depend on guessing rules.

The controller

The controller creates the form, hands it the request, and decides what to do. Note how thin it is:

PHP
<?php
// src/Controller/TaskController.php

namespace App\Controller;

use App\Entity\Task;
use App\Form\TaskType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class TaskController extends AbstractController
{
    #[Route('/tasks/new', name: 'task_new', methods: ['GET', 'POST'])]
    public function new(Request $request): Response
    {
        $task = new Task();

        $form = $this->createForm(TaskType::class, $task);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // $task now holds the submitted data: save it, send it, queue it...
            $this->addFlash('success', 'Task saved.');

            return $this->redirectToRoute('task_new');
        }

        return $this->render('task/new.html.twig', [
            'form' => $form,
        ]);
    }
}

The same action handles both methods. A GET request renders the empty form. A POST is read by handleRequest(), which looks at the request method and the form's field values (they arrive nested under the form name, as task[title], derived from the class name TaskType). After submission, $task is filled in. When the submission is valid you act on it and redirect, so a browser refresh does not resubmit the form. When it is invalid, you render the template again; in modern Symfony, render() automatically answers with status 422 Unprocessable Content if the form was submitted and invalid, which is what tools like Turbo expect. The full submission flow is the topic of Handling Submission and CSRF.

For a quick form that has no class (a search box, a contact form that is not stored), use the builder in the controller. The data is an array:

PHP
$form = $this->createFormBuilder(['query' => ''])
    ->add('query', SearchType::class)
    ->add('go', SubmitType::class)
    ->getForm();

Rendering in Twig

In the template you can print the whole form at once:

TWIG
{# templates/task/new.html.twig #}
{% extends 'base.html.twig' %}

{% block body %}
    <h1>New task</h1>
    {{ form(form) }}
{% endblock %}

form() prints the <form> tag, every field with its label and errors, and the CSRF field. That is perfect for prototypes. For real pages you usually want more control, so Twig offers smaller functions:

TWIG
{{ form_start(form, {'attr': {'novalidate': 'novalidate'}}) }}
    {{ form_errors(form) }}              {# errors that belong to the whole form #}

    {{ form_row(form.title) }}           {# label + widget + errors + help #}

    <div class="row">
        {{ form_label(form.dueDate) }}
        {{ form_widget(form.dueDate, {'attr': {'class': 'date-input'}}) }}
        {{ form_errors(form.dueDate) }}
        {{ form_help(form.dueDate) }}
    </div>

    {{ form_row(form.done) }}
    {{ form_row(form.save) }}
{{ form_end(form) }}
Function Prints
form_start(form) / form_end(form) The opening and closing form tags (form_end also renders any fields you forgot, through form_rest)
form_row(field) Label, widget, errors and help for one field
form_label(field) Only the label
form_widget(field) Only the input element
form_errors(field) Only the error list
form_help(field) The help text from the help option
form_rest(form) All fields not rendered yet

The form variable that your controller passes is turned into a view with the same shape as the form, so form.title is the view of the title field. Passing the $form object directly to render() is enough: Symfony converts it for you.

Adding 'novalidate' to the form tag turns off the browser's own checks so you can see the server-side messages while learning. In production, keeping browser validation as a first line of feedback is fine, but the server must always validate.

Form themes

A form theme is a Twig template that defines blocks for how each piece is rendered: form_row, text_widget, form_errors and so on. The default theme, form_div_layout.html.twig, produces plain <div> rows with no CSS classes. Symfony ships with themes for popular CSS frameworks, and you pick one globally in the Twig configuration:

YAML
# config/packages/twig.yaml
twig:
    form_themes: ['bootstrap_5_layout.html.twig']

Other built-in themes include bootstrap_5_horizontal_layout.html.twig, tailwind_2_layout.html.twig and foundation_6_layout.html.twig. You can also apply a theme to one form in a template, or write your own file that overrides only the blocks you care about:

TWIG
{# templates/form/my_theme.html.twig #}
{% use 'form_div_layout.html.twig' %}

{% block form_row %}
    <div class="field">
        {{ form_label(form) }}
        {{ form_widget(form) }}
        {{ form_errors(form) }}
    </div>
{% endblock %}
TWIG
{% form_theme form 'form/my_theme.html.twig' %}
{{ form(form) }}

Because a theme is defined by blocks, you can restyle every form on your site by changing one file, and you never repeat label-and-error markup in each template.

A runnable stand-in

Symfony cannot run on this site, so the following examples rebuild the same flow in plain PHP: a Task data class, a TaskType with buildForm(), a tiny FormBuilder, a Form that reads a POST array, and a renderer. The real component is far more capable, but the shape (describe, handle, render) is identical. The first example only renders, including HTML escaping of a value with markup in it.

PHP Describing and rendering a form (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 name task comes from the class name TaskType, which is where field names such as task[title] come from in real Symfony too. The title containing markup is escaped, as Symfony's Twig rendering does automatically.

The second example handles a request: a GET leaves the object untouched, while a POST fills it. It also shows that an unchecked checkbox sends nothing at all, so absence means false.

PHP Handling a request (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.

In the second case the default done = true becomes false because a submitted form with no checkbox value means "unchecked". The real component behaves the same way, which is why you must think about defaults when you pre-fill a form.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which class do you extend to describe a reusable Symfony form?

    A form type extends AbstractType and implements buildForm() to add fields, and optionally configureOptions() to set options such as data_class.
  2. 2. What does $form->handleRequest($request) do?

    handleRequest() checks the method and the submitted fields; if the form was submitted it fills the data. You then check isSubmitted() and isValid().
  3. 3. Which Twig function prints the label, widget, errors and help text of one field?

    form_row() renders the whole row for a field. form_widget() prints only the input element, and form_rest() prints fields you have not rendered yet.
  4. 4. How do you make every form on the site use Bootstrap 5 markup?

    A form theme defines the blocks used to render fields. Setting it in config/packages/twig.yaml applies it globally.
  5. 5. After a valid submission, what should the controller normally do?

    Redirecting (Post/Redirect/Get) prevents the browser from resubmitting the form when the user refreshes the page.

Summary

  • A form is a class extending AbstractType; buildForm() adds fields (name, type, options) and configureOptions() sets options such as data_class.
  • The controller calls createForm(), handleRequest(), then checks isSubmitted() && isValid(); after success it redirects, otherwise it renders the form again.
  • The form name comes from the class (TaskType becomes task), so fields arrive as task[title] and the request data is mapped through PropertyAccess.
  • In Twig, form() prints everything, while form_start, form_row, form_widget, form_errors and form_end give you control.
  • Form themes are Twig block files; set one globally in twig.form_themes or apply one with {% form_theme %}.

Next up: Form Types and Options.