17

I am using symfony and I want to get the url of a specific route , my route is like this

project_sign_in:
    pattern:  /signin
    defaults: { _controller: ProjectContactBundle:User:signIn }

i want to generate the url from this route so i can get

localhost/app_dev.php/signin or {SERVER-ADDRESS}/app_dev/signin

if I was browsing the server.

Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
user2784013
  • 253
  • 1
  • 5
  • 14
  • Does this answer your question? [How can i get full url to include in newsletter sent with Symfony2?](https://stackoverflow.com/questions/10621068/how-can-i-get-full-url-to-include-in-newsletter-sent-with-symfony2) – A.L Jan 10 '20 at 15:33

4 Answers4

25

Using the Routing Component at version 4.0:

<?php
use Symfony\Component\Routing\Generator\UrlGenerator;

UrlGenerator->generate('project_sign_in', [], UrlGenerator::ABSOLUTE_URL);
Michael B.
  • 899
  • 10
  • 16
17

The last facultative parameter has to be true to generate absolute url:

$router->generate('project_sign_in', array(), true);

in twig:

{{ path('project_sign_in', {}, true) }}
{# or #}
{{ url('project_sign_in') }}

in controller:

$this->generateUrl('project_sign_in', array(), true );

EDIT: for symfony 4, see @Michael B. answer
UrlGenerator->generate('project_sign_in', [], UrlGenerator::ABSOLUTE_URL);

goto
  • 7,908
  • 10
  • 48
  • 58
8

In Symfony 5.0, if you are using Routing within a service:

namespace App\Service;

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
.
.
.
private $router;

public function __construct(UrlGeneratorInterface $router)
{
    $this->router = $router;
}

public function foo()
{
    $this->router->generate('bar', [], urlGeneratorInterface::ABSOLUTE_URL);
}
0

At least with Symfony 6, the controller has a builtin method ready for that:

$signUpPage = $this->generateUrl('sign_up');

See https://symfony.com/doc/current/routing.html#generating-urls-in-controllers

yhu420
  • 436
  • 6
  • 18