#[MapQueryParameter] in Symfony: reading and filtering the query string
The #[MapQueryParameter] attribute passes a query string parameter to a Symfony controller action, converted to the argument's type and filtered.
#[Route('/reservation', name: 'app_reservation')] public function index( #[MapQueryParameter(options: ['min_range' => 1, 'max_range' => 12], validationFailedStatusCode: Response::HTTP_BAD_REQUEST)] int $personnes = 2, ): Response { return $this->render('reservation/index.html.twig', ['personnes' => $personnes]); }
The argument's name gives the parameter's name, name lets you pick another one. The declared type, int, float, bool, string or array, sets the filter_var() filter applied to the value; options, flags and filter refine it, like min_range and max_range above. A default value or a nullable type make the parameter optional. No more $request->query->get() followed by a cast and hand-written checks: ?personnes=dragon never reaches the action. The trap: when the value is rejected, Symfony answers 404 by default, not 400. That's on purpose for pagination, where ?page=abc points to a page that doesn't exist, but to report an invalid request you have to ask for it with validationFailedStatusCode.
The exercises have you read a booking's number of guests from ?personnes=, between 1 and 12, 2 by default and a 400 error outside those bounds, then paginate the tavern's guestbook with ?page=: ten reviews per page, a 404 for a page that is zero, not a number or too far, and a database that only returns the page's reviews.
2 exercises work on this concept, by writing code in the browser.
In the tracks
- How many adventurers? Symfony for PHP developers · chapter 1: First steps at the tavern
- The big guestbook Symfony for PHP developers · chapter 8: Back to the cellar