Saturday 16 June 2012

Get the current route and url in a Symfony 2 controller

Problem:

How do I get the current page's URL and current route in a Symfony 2 controller?

Solution:

There are several ways to get the current page's route and url. One way is demonstrated here.

Current route

public function someAction(Request $request){
  // ... some code here

  $currentRoute = $request->attributes->get('_route');

  // more code ...
}
Current URL

public function someAction(Request $request){
  // ... some code here
  
  $currentRoute = $request->attributes->get('_route');
  $currentUrl = $this->get('router')
                     ->generate($currentRoute, array(), true);
  
  // more code ...
}
Updated:

Alternatively, you can also generate the current URL directly without using the current route (thanks COil for the comment!)


$currentUrl = $this->getRequest()->getUri();

$currentUrl = $request->getUri();
//(see comments below, thanks Marcos for the comment!)


Notes:

This was tested to work using Symfony2 version 2.0.4.

Reference:

http://symfony.com/doc/current/book/routing.html#generating-urls

5 comments:

  1. Hi !

    For the current URL you should use:

    $currentUrl = $this->getRequest()->getUri();

    So you don't have to re-generate the URL with the route parameter.

    I have created a mini-cheatsheet on my blog:

    --> http://www.strangebuzz.com/post/2012/03/01/%5BSymfony2%5D-Request-class-mini-cheatsheet

    See you. COil

    ReplyDelete
  2. It seems $this->getRequest()->getUri(); is deprecated atm.

    Inject Request in the controller and call $request->getUri(); directly

    ReplyDelete
  3. Thanks @Marcos for the comment and API update. The above post was written quite some time ago :) It's been updated now.

    ReplyDelete