Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 62 ยท Forms and Validation

Handling Submission and CSRF

Handle Symfony form submissions correctly with isSubmitted, isValid, flash messages and redirects, show errors, and understand how CSRF protection works.

Building and rendering a form is the easy half. The part that decides whether your site is correct and safe is what happens when the user presses the button: is this request really a submission of this form, is the data valid, what do you do on success, what do you show on failure, and how do you know the request came from your own page and not from a malicious site?

This lesson follows one submission from request to response. It explains isSubmitted() and isValid(), the Post/Redirect/Get pattern with flash messages, how errors are collected and displayed, and CSRF protection, the mechanism that stops other websites from submitting your forms on a visitor's behalf. Real Symfony code is read-only; the runnable examples are plain-PHP stand-ins that follow the same flow.

The standard controller pattern

You saw this skeleton in Forms: Building and Rendering. Here it is again, with the reasons for each line:

PHP
#[Route('/tasks/new', name: 'task_new', methods: ['GET', 'POST'])]
public function new(Request $request, EntityManagerInterface $entityManager): Response
{
    $task = new Task();
    $form = $this->createForm(TaskType::class, $task);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $entityManager->persist($task);
        $entityManager->flush();

        $this->addFlash('success', 'Task saved.');

        return $this->redirectToRoute('task_show', ['id' => $task->getId()]);
    }

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

handleRequest() decides whether this request is a submission of this form. It compares the request method with the form's method (POST by default), and for a named form it also requires the form's name key (task) in the request data. If both match, the form is marked as submitted and the data is read, converted and written to the object. Otherwise nothing happens, and the form just keeps its initial data, which is how the same action serves both the empty form (GET) and the submission (POST).

Always check isSubmitted() before isValid(). A form that was never submitted has no data to validate, and in recent Symfony versions calling isValid() on a form that was not submitted is an error, not just false.

There are three outcomes:

Situation What you do
Not submitted (first visit) Render the form
Submitted and valid Use the data, add a flash message, redirect
Submitted and invalid Render the form again, with errors and the user's input

When you return $this->render(...) with a submitted-and-invalid form, Symfony sends status 422 Unprocessable Content instead of 200. That matters for tools such as Hotwire Turbo, which only swaps the page content for a response with an error status, and it is also the semantically right answer for a rejected submission.

Post/Redirect/Get and flash messages

After a successful POST, redirect. If you rendered a page directly instead, the browser would remember the POST, and pressing refresh (or the back button) would send the form again: a second order, a second comment. A redirect turns the final page into a harmless GET.

The redirect loses the request, though, so how do you tell the user "Task saved"? With a flash message: a value stored in the session that survives exactly one more request and then disappears.

PHP
$this->addFlash('success', 'Task saved.');
return $this->redirectToRoute('task_show', ['id' => $task->getId()]);
TWIG
{# templates/base.html.twig #}
{% for message in app.flashes('success') %}
    <div class="alert alert-success">{{ message }}</div>
{% endfor %}

Reading flashes in Twig removes them from the session, which is why the message appears once. Use any label you like (success, warning, error) and style each differently. Sessions and flash storage are covered in Sessions and Flash Messages.

sequenceDiagram
    participant B as Browser
    participant S as Symfony
    B->>S: GET /tasks/new
    S-->>B: 200 form (with CSRF token)
    B->>S: POST /tasks/new (invalid)
    S-->>B: 422 form with errors
    B->>S: POST /tasks/new (valid)
    S-->>B: 302 Location /tasks/7 (flash stored)
    B->>S: GET /tasks/7
    S-->>B: 200 page + flash message shown once

A failed submission re-renders the form with status 422; a successful one ends in a redirect and a one-time flash message.

Errors and how to show them

Errors come from two sources: a field whose text cannot be converted (a date such as 2030-02-31) and the validator's constraints (covered in Validation). Each error is attached to the field it belongs to, or to the form as a whole.

In Twig, form_row() prints a field's errors next to it, and form_errors(form) prints errors that belong to the form itself (CSRF failures, for example). In PHP you can inspect them:

PHP
foreach ($form->getErrors(true) as $error) {      // true = include children, deep
    echo $error->getOrigin()->getName(), ': ', $error->getMessage(), "\n";
}

You can add your own errors, for example when a business rule fails after the form itself is valid:

PHP
use Symfony\Component\Form\FormError;

if ($taskRepository->titleExists($task->getTitle())) {
    $form->get('title')->addError(new FormError('You already have a task with this title.'));
}

Check $form->isValid() again afterwards, or structure the code so that this check happens before the "success" branch. Prefer validation constraints for rules that depend only on the data; custom errors in the controller are for rules that need services or context.

Several buttons

A form can have more than one submit button. Add them as SubmitType fields and ask which was used:

PHP
$builder->add('save', SubmitType::class)->add('saveAndAdd', SubmitType::class);
PHP
if ($form->isSubmitted() && $form->isValid()) {
    // ...
    $next = $form->get('saveAndAdd')->isClicked() ? 'task_new' : 'task_index';
    return $this->redirectToRoute($next);
}

$form->getClickedButton() returns the clicked button object (or null). Because buttons are fields in the form, the button name is part of the submitted data.

Submitting data that did not come from a browser form

For JSON APIs and tests you do not need handleRequest(). Call submit() with an array yourself:

PHP
$data = json_decode($request->getContent(), true);
$form->submit($data);                 // missing fields are set to null
$form->submit($data, false);          // false = keep existing values for missing fields (PATCH)

Disable CSRF protection for such forms with the option 'csrf_protection' => false, because API clients authenticate with tokens or other means, not with a browser session cookie. For JSON APIs, Mapping Request Data to Objects is often a simpler tool than the Form component.

CSRF protection

Cross-Site Request Forgery is an attack on forms that rely on the browser's cookies. Suppose you are logged in at shop.example. You visit evil.example, which contains a hidden form that posts to https://shop.example/account/delete. Your browser dutifully attaches your session cookie, and the shop sees a perfectly authenticated request.

The defence is a secret the attacker cannot know. Symfony adds a hidden field named _token to every form. Its value is a CSRF token tied to the user's session and to a token id (by default the form's name). When the form is submitted, Symfony compares the token from the request with the expected one. A forged request from another site cannot read your page (the browser's same-origin policy forbids it), so it cannot include the token, and the form fails validation:

TEXT
The CSRF token is invalid. Please try to resubmit the form.

The protection is on by default for forms when the Security CSRF component is available (the framework.csrf_protection option, enabled by the standard recipe). You can adjust it per form:

PHP
public function configureOptions(OptionsResolver $resolver): void
{
    $resolver->setDefaults([
        'data_class' => Task::class,
        'csrf_protection' => true,
        'csrf_field_name' => '_token',
        'csrf_token_id' => 'task_item',
    ]);
}

Newer Symfony versions can also check tokens without a session (a "stateless" mode that uses a cookie and a header), which helps cached pages; see the framework configuration reference for your version if you need it.

Three practical consequences:

  • A token is valid only for the session that received it. If the session expires while a user fills a long form, the submission fails with the CSRF message; show a friendly way to try again.
  • Pages that contain forms are therefore per-user pages. Do not serve them from a shared cache.
  • SameSite=Lax session cookies (the Symfony default) block many cross-site POST requests as well, but treat that as a second layer, not a replacement for tokens.

CSRF outside the Form component

Links and buttons that change data (a "Delete" button in a list) are not part of a Symfony form but need the same protection. Generate a token in Twig and check it in the controller:

TWIG
<form method="post" action="{{ path('task_delete', {id: task.id}) }}">
    <input type="hidden" name="_token" value="{{ csrf_token('delete-task-' ~ task.id) }}">
    <button type="submit">Delete</button>
</form>
PHP
#[Route('/tasks/{id}/delete', name: 'task_delete', methods: ['POST'])]
public function delete(Task $task, Request $request, EntityManagerInterface $entityManager): Response
{
    if (!$this->isCsrfTokenValid('delete-task-' . $task->getId(), $request->getPayload()->getString('_token'))) {
        throw $this->createAccessDeniedException('Invalid CSRF token.');
    }

    $entityManager->remove($task);
    $entityManager->flush();

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

Using the item's id in the token id makes the token specific to that one action, so a token leaked from one form cannot be used for another. And notice the method: destructive actions must be POST (or DELETE), never GET, because GET requests can be triggered by images and links.

A runnable CSRF stand-in

Real Symfony stores a random token per token id in the session. To keep the output deterministic, this stand-in derives the token with an HMAC of the token id and session id instead, which has the same visible effect: a token works only for its own session and its own token id, and any change makes it fail.

PHP How a CSRF token is checked (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 attacker's page can send a POST with Alice's cookie, but it cannot learn Alice's token, so the forged request lands in one of the REJECTED rows.

A runnable submission flow

The second stand-in is a miniature controller with the full flow: a GET renders the form, an invalid POST returns 422 with errors, a POST with a bad CSRF token is rejected as a form-level error, and a valid POST redirects with a flash message that is shown exactly once.

PHP Post/Redirect/Get with errors and flash messages (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.

Notice that the refresh in the last request does not create a second task and that the flash appears only once. The invalid submissions all return 422 and never touch the stored tasks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a successful form submission end with a redirect?

    Post/Redirect/Get replaces the final page with a GET request, so a refresh or the back button cannot send the form data a second time.
  2. 2. Which check order is correct?

    A form that was not submitted has nothing to validate, so check isSubmitted() first, then isValid().
  3. 3. What does a flash message do?

    Flash messages live in the session for exactly one more request, which makes them ideal for a message after a redirect.
  4. 4. How does a CSRF token stop a forged request from another website?

    The browser sends cookies automatically, but the same-origin policy keeps the attacker's page from reading your form and its token. Without the token the request fails.
  5. 5. A submitted-and-invalid form is rendered with $this->render(). Which status does Symfony send?

    Recent Symfony versions answer a submitted but invalid form with 422, which is correct semantically and required by tools such as Turbo.

Summary

  • handleRequest() decides whether the request submits this form; check isSubmitted() && isValid() and then act.
  • On success, add a flash message and redirect; on failure, render the form again (status 422) so the user's input and the errors are shown.
  • Errors attach to fields or to the form; read them with getErrors(true) and add your own with addError(new FormError(...)).
  • For APIs call $form->submit($data) (use false as the second argument for PATCH-like partial updates) and disable CSRF for token-authenticated clients.
  • CSRF tokens (_token) prove that a request came from your own page; use csrf_token() and isCsrfTokenValid() for delete buttons and other actions outside forms, and never change data on GET.

Next up: Advanced Forms.