Not just anything on the plate

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

Topics covered: ValidatorConstraintsUniqueEntity

The form is gorgeous… and it accepts anything. Pippin has already added a dish with no name, a “Soup” at −3 gold pieces (the tavern was paying him to eat it), and a second “Dwarf Stew”, which crashed the database because of the duplicate slug.

Rather than checking each field in the controller, you declare the rules on the entity: the Validator component will apply them wherever a Plat is validated (forms, API, commands…).

Your mission

Add the following constraints to the Plat entity, with these messages:

Property Rule Message
nom (name) required, 100 characters at most “Give the dish a name.”
description required, at least 10 characters “Describe the dish in at least 10 characters.”
prix (price) required “Enter a price.”
prix strictly positive “The price must be greater than zero.”
categorie (category) required “Choose a category.”
the dish no two dishes with the same name “This dish is already on the menu.”

The controller and the form don't need to change: $form->isValid() applies your constraints, and form_widget displays the errors next to the fields.

Reminder

Most constraints ignore empty values: Positive accepts a null price! That's on purpose (constraints are meant to be combined), hence NotBlank to make a field required. Without it, an empty price would pass validation… and the database would refuse to save it.

Without a custom message, Symfony displays a default message (“This value should not be blank.”). Try it: leave the description empty.