Posting a classified ad

Exercise 4 of 7 in chapter 6 · 200 XP · 5 objectives checked by tests

Topics covered: FormsPOST method$_POSTValidation422

Madame Lou is drowning in little notes slipped into her mailbox: “Wheelbarrow for sale”, “Looking for a ginger cat”… From now on, the villagers will post their classified ads online. Odette's nephew has already designed the form, in templates/proposer-annonce.php (submit an ad): it expects $valeurs (values), what was typed, and $erreurs (errors), the list of problems.

Your mission

  1. Add to Annonce a static method valider(array $valeurs): array (validate) that returns the list of errors, empty if everything is fine:
    • The title is required. if the title is empty;
    • The price is required. if the price is empty, otherwise “forty” is not a price: write a whole number of euros., where “forty” is what was typed, if it does not contain only digits;
    • The contact is required. if the contact is empty.
  2. Declare the /ads/submit route, for GET and POST. With GET, it displays the empty form, in a page whose tab reads Post a classified ad — The Saint-Glinglin Gazette.
  3. With POST, read the three fields from $_POST (without the spaces around them) and validate them. If there are errors, respond with 422 and display the form again with what was typed.
  4. Otherwise, display templates/annonce-envoyee.php (ad sent), which you write: inside a <main class="lecture">, <p class="confirmation">Thank you! Your ad will appear in the next issue.</p>, then the ad itself.
  5. In the menu, add an <a class="proposer"> link, “Post an ad”.

The ads are not saved yet: that will take a database, in the next track.

Reminder

A form with method="post" sends its fields in the body of the request, and PHP puts them in $_POST, indexed by the name attribute of the fields. $_SERVER['REQUEST_METHOD'] is 'GET' or 'POST' depending on the request, and $r->addRoute(['GET', 'POST'], …) declares a route that answers both.

A few tools to read and check what was typed:

The 422 status code (Unprocessable Content) says “I understood the request, but it is not valid”: it is the usual response to a rejected form.

valider() and the set hook on the price (exercise 13) complement each other. valider() explains to the person what is wrong with what they typed: “-5” does not contain only digits, so it is rejected with a message. The hook, for its part, guarantees that an Annonce will never have a negative price, whatever code creates it. The first talks to the user, the second protects the program.