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
- Posting a classified ad Learn PHP 8 from scratch · chapter 6: The Gazette is online
- A proper form Symfony for PHP developers · chapter 3: The tavern's scrolls
- The guestbook Symfony for PHP developers · chapter 3: The tavern's scrolls
- 🐉 Boss: the cursed scroll Symfony for PHP developers · chapter 3: The tavern's scrolls
- The story night poster Symfony for PHP developers · chapter 12: The big night
- Sign-ups Symfony for PHP developers · chapter 12: The big night
In Practice
- Grouping the steps of a multi-step form Symfony 8.2 nests the steps of a form flow: createStepGroup() brings the company and billing steps together, and a single setSkip() skips both for an individual.
- A JSON array in a text field, with allow_array_submission A text field receiving a JSON array was rejected before any listener. allow_array_submission lets PRE_SUBMIT transform it first.
- Help text under each choice, with choice_help choice_help gives each radio button its own help text, linked by aria-describedby: short labels, and explanations that screen readers read with the right choice.
- A collection of blocks of several kinds PolymorphicCollectionType gives each entry of a collection the form of its kind: titles, paragraphs and quotes in the same page.
- A form for an immutable object Symfony 8.2 calls the constructor of a readonly class: no more intermediate array or copied constraints, but a new object to read from getData().
- A form that reads PHP types ->add('seats') is enough: Symfony 8.2 infers the field type and its empty_data from the property's type, and an empty field no longer causes a TypeError.
- One field for a date range, with BoundsType Two dates and the rule that orders them fit in a single field: no more POST_SUBMIT listener comparing the bounds by hand.
- Describing a form with attributes A form's fields are declared on the DTO, right next to the validation constraints: no more form class for simple cases.