Symfony forms: create, handle and render a form

A Symfony form is described in a form type class bound to an object; the Form component handles the HTML, reading the request and the CSRF token.

#[Route('/cuisine/nouveau-plat', name: 'app_nouveau_plat', methods: ['GET', 'POST'])]
public function nouveauPlat(Request $request, EntityManagerInterface $entityManager, SluggerInterface $slugger): Response
{
    $plat = new Plat();
    $form = $this->createForm(PlatType::class, $plat);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $plat->setSlug($slugger->slug($plat->getNom())->lower()->toString());
        $entityManager->persist($plat);
        $entityManager->flush();

        return $this->redirectToRoute('app_plat', ['slug' => $plat->getSlug()]);
    }

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

The form type, an AbstractType with buildForm() and data_class, declares the fields: TextType, IntegerType, or EntityType with choice_label to pick a category from the database. handleRequest() fills the object, isSubmitted() and isValid() decide what happens next, and Twig renders it all with form_start(), form_widget() and form_end(). Rendered again after an invalid submission, the form goes out with a 422 status. Symfony 8.2 adds BoundsType for a period and #[AsFormType] to describe the fields on a DTO. The trap: forgetting handleRequest(). isSubmitted() stays false, and the form is displayed again without saving or reporting anything.

The exercises have you replace a hand-written form with a PlatType, add the guestbook review form, lift the curse of a form that no longer does anything, schedule storytelling evenings and register travellers without going over the number of seats, then discover BoundsType and describing a form with attributes.

14 exercises work on this concept, by writing code in the browser.

In the tracks

In Practice

Related concepts

CSRFDTO$_POSTValidation422RelationsDebuggingSecurity