symfony 4/5 controller/action Cheatsheet
Get Request Params
https://symfony.com/doc/5.4/controller.html#the-request-and-response-object
- $request->headers->all()
- GET: $request->query->all()
- POST: $request->request->all()
- e.g. JSON payload: $request->getContent() + json_decode()
- $request->server->all()
Get env/debug
-
$this->getParameter('kernel.environment') // prod, dev $this->getParameter('kernel.debug') // true, false
Error Handling / 404 / 500
https://symfony.com/doc/current/controller.html#managing-errors-and-404-pages
https://symfony.com/doc/5.4/controller/error_pages.html
-
// In a controller action if (!$foo)) { throw $this->createNotFoundException('No foo going on!'); }
Custom error page:
- Create "templates/bundles/TwigBundle/Exception/error.html.twig"
-
{% extends 'base.html.twig' %} {# Test with http://localhost:8040/_error/404 #} {% block body %} <h1>{{ status_code }} - Sorry, something went wrong...</h1> <p> <a href="/">Back to homepage</a>. </p> <script> setTimeout(() => { window.location.href = '/'; }, 2000); </script> {% endblock %}
-
Redirect
-
return $this->redirect($fixedUrl, 301);
Redirect directly from a controller subroutine:
-
$redirectResponse = $this->redirect($fixedUrl, 301); $redirectResponse->send();