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();

Generate URL

  • $this->generateUrl('fooRouteName', [
        'foo' => 'bar',
    ], 1); // 1 = ABSOLUTE_PATH e.g. "/dir/file"

Generate URL outside controller, eg. in repository

  • class FooRepository extends ServiceEntityRepository
    {
        private $router;
    
        public function __construct(RouterInterface $router)
        {
            $this->router = $router;
    
            parent::__construct($registry, Foo::class);
        }
    
        public function bar() {
            $this->router->generate(...); // Same method as "generateUrl()" in controller
        }

Use Doctrine / EntityManager

  • // In a symfony controller inject the entity manager:
    public function test(EntityManagerInterface $em) {   
    
        $country = new Country();
        $country->setName('Foo');
    
        $em->persist($country);
        $em->flush();
    }