Grégoire Pineau Nicolas Grekas
Contributed by Grégoire Pineau and Nicolas Grekas in #41178 and #41190

The recommended way of processing Symfony forms is to use a single action for both rendering the form and handling the form submit.

This is how it looks in practice:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/Controller/ConferenceController.php
// ...
#[Route('/{id}/edit', name: 'conference_edit', methods: ['GET', 'POST'])]
public function edit(Request $request, Conference $conference): Response
{
    $form = $this->createForm(ConferenceType::class, $conference);

    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        // do something with the $conference object
        // (e.g. persist it in the database)

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

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

When using libraries such as Symfony UX Turbo this simple form handling is not enough and you have to follow the HTTP protocol strictly (e.g. if the form is submitted but invalid, the response must have a HTTP 422 status code).

In order to simplify the form handling in those cases, Symfony 5.3 adds a new (optional) helper to render forms. This helper is defined in the AbstractController base controller as a new method called renderForm().

This is how the last lines of the previous example should be written when using the new helper:

1
2
3
4
5
6
7
// src/Controller/ConferenceController.php
// ...

    return $this->renderForm('conference/edit.html.twig', [
        'form' => $form,
    ]);
}

The signature of the renderForm() method is the same as for render():

1
2
3
4
5
renderForm(
    string $view,
    array $parameters = [],
    Response $response = null
): Response

This method renders the given form (it calls $form->createView() internally) and sets the 422 status code when the form is submitted and invalid.

The $parameters argument is the list of variables passed to the Twig template and the optional $response object allows you to configure certain properties of the returned response (e.g. its cache options).

Published in #Living on the edge