Symfony - generate url with parameter in controller

user2094540 picture user2094540 · Nov 18, 2013 · Viewed 130.7k times · Source

I want to generate a Url directly in my controller. I want to user a url defined in my routing.yml file that needs a parameter.

I've found that code in the Cookbook (Routage section) :

$params = $router->match('/blog/my-blog-post');
// array('slug' => 'my-blog-post', '_controller' => 'AcmeBlogBundle:Blog:show')

$uri = $router->generate('blog_show', array('slug' => 'my-blog-post'));
// /blog/my-blog-post

But I don't understand to what is refering the $router. Obviously, it doesn't work. Is there a simple way to generate a routing url with a paramter in a controller ?

Answer

Sybio picture Sybio · Nov 18, 2013

It's pretty simple :

public function myAction()
{
    $url = $this->generateUrl('blog_show', array('slug' => 'my-blog-post'));
}

Inside an action, $this->generateUrl is an alias that will use the router to get the wanted route, also you could do this that is the same :

$this->get('router')->generate('blog_show', array('slug' => 'my-blog-post'));