6

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.

2 Answers 2

7

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
    Commented Jan 23, 2015 at 9:57
  • Use the getRouteName() method.
    – Berdir
    Commented Jan 23, 2015 at 10:54
4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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