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 ...
}
public function someAction(Request $request){
// ... some code here
$currentRoute = $request->attributes->get('_route');
$currentUrl = $this->get('router')
->generate($currentRoute, array(), true);
// more code ...
}
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.
Hi !
ReplyDeleteFor 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
Thanks! Updated :)
ReplyDeleteIt seems $this->getRequest()->getUri(); is deprecated atm.
ReplyDeleteInject Request in the controller and call $request->getUri(); directly
Thanks @Marcos for the comment and API update. The above post was written quite some time ago :) It's been updated now.
ReplyDeleteThanks.
ReplyDelete