5

If I know the internal path of my page (e.g. 'node/1') how do I get the router name?

I need it it to generate an internal url:

$url = Url::fromRoute($router_name);

I found Url::getRouteName, but I'm not sure if this is what I need?

Thanks.

5

Have a look at PathValidatorInterface::getUrlIfValid() or the version that does not check access. That is provided by the path.validator service:

\Drupal::service('path.validator')->getUrlIfValid('node/1')
2
  • Thanks. That gets me the url object, but when I try to reference $url_object->routhName I get an error: Cannot access protected property Drupal\Core\Url::$routeName.
    – dbj44
    Jan 23 '15 at 9:57
  • Use the getRouteName() method.
    – Berdir
    Jan 23 '15 at 10:54
3

You can also do like this

$route_name = Url::fromUserInput($internal_path)->getRouteName();

More details : http://www.drupal8.ovh/en/tutoriels/275/drupal-8-url-tips-get-name-path-args

0

As an alternative to the above solution if you are having a dynamic page use this

\Drupal::request()->get(Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_NAME)

Using the above answer for dynamic pages will be

\Drupal::service('path.validator')->getUrlIfValid('node/*')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.