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
- Add to
Annoncea static methodvalider(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.
- Declare the
/ads/submitroute, forGETandPOST. WithGET, it displays the empty form, in a page whose tab readsPost a classified ad — The Saint-Glinglin Gazette. - 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. - 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. - 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:
$_POST['titre'] ?? ''gives the field, or''if it was not sent (without the “Undefined array key” warning);trim($texte)removes the spaces at the beginning and the end;ctype_digit($texte)istrueif the string contains only digits (and is not empty);(int) $texteturns'40'into the integer40.
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.