0

I'm doing this:

$link = $node->field_link->first();
if ($link) {
  $url = $link->getUrl()->toString();
  ...
}

If the value in the link field is /node/123 but there is a URL alias defined as:

Alias: /about-us    System path: /node/123

I get /about-us in $url. I want to get /node/123.

How do I get the raw url value instead of the aliased value?

5

Instead of rendering the URL object with toString() use the method Url::getInternalPath:

$url = $link->getUrl();
if ($url->isRouted()) {
  $path = $url->getInternalPath();
}
0

Another solution I happened upon since I first posted is

$uri = $node->get('field_link')->uri;

The difference between this and the accepted answer is that this approach gives the actual, raw value in the link field (with 'internal:' appended to the front) whatever it is, without URL alias translation. The accepted answer doesn't translate /node/123 in the field to /about-us, but it does translate /about-us in the field to /node/123.

Once $uri has been modified as needed, it can be put back into the node by

$node->set('field_link', ['uri' => $uri]);

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.