A proper form

Exercise 1 of 6 in chapter 3 · 180 XP · 5 objectives checked by tests

Topics covered: FormsFormTypeEntityTypeCSRF

Take another look at Bruna's CuisineController: read each field, convert the price, find the category, redisplay the submitted values… Sixty lines for a single form. And more forms are coming soon (editing a dish, leaving a review).

Symfony has a component for that: Form. You describe the form once, in a class, and Symfony takes care of the HTML, reading the request, converting values and CSRF protection.

Your mission

  1. Complete App\Form\PlatType, bound to the Plat (dish) entity: fields nom (name), description (a text area), prix (price, a number), specialite (specialty, an optional checkbox) and categorie (category), chosen from the database and displayed by its name.
  2. Rewrite CuisineController::nouveauPlat() with this form: when it is submitted and valid, give the dish a slug made from its name, save it, then redirect to its page.
  3. Display the form in cuisine/nouveau.html.twig, with an “Add to the menu” button.

Reminder

$form->handleRequest($request) fills the Plat object with the submitted data. You no longer have to read $request->request yourself. The hidden _token field protects the form against requests forged from another site (CSRF): Symfony checks it on its own.

Data validation (a required name, a positive price…) is the topic of the next exercise.