Symfony - generate url with parameter in controller

SymfonySymfony Routing

Symfony Problem Overview


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 ?

Symfony Solutions


Solution 1 - Symfony

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

Solution 2 - Symfony

If you want absolute urls, you have the third parameter.

$product_url = $this->generateUrl('product_detail', 
    array(
        'slug' => 'slug'
    ),
    UrlGeneratorInterface::ABSOLUTE_URL
);

Remember to include UrlGeneratorInterface.

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

Solution 3 - Symfony

Get the router from the container.

$router = $this->get('router');

Then use the router to generate the Url

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

Solution 4 - Symfony

make sure your controller extends Symfony\Bundle\FrameworkBundle\Controller\Controller;

you should also check app/console debug:router in terminal to see what name symfony has named the route

in my case it used a minus instead of an underscore

i.e blog-show

$uri = $this->generateUrl('blog-show', ['slug' => 'my-blog-post']);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2094540View Question on Stackoverflow
Solution 1 - SymfonySybioView Answer on Stackoverflow
Solution 2 - SymfonyPedro CasadoView Answer on Stackoverflow
Solution 3 - SymfonyJon WinstanleyView Answer on Stackoverflow
Solution 4 - SymfonyEdwin O.View Answer on Stackoverflow