Symfony - generate url with parameter in controller Symfony - generate url with parameter in controller symfony symfony

Symfony - generate url with parameter in controller


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


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;


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