1

Suppose I have a link field for internal images. $node->file_image->uri will for instance return:

internal:/sites/default/files/image/image.jpeg

I need to convert this into an absolute URL for metadata. I can do this manually, of course, but let's see what the usual functions do:

file_create_url() = "https://example.com/internal%3A/sites/default/files/image/image.jpeg"
file_build_uri() = "public://internal:/sites/default/files/image/image.jpeg"
file_create_url(file_build_uri()) = "https://example.com/sites/default/files/internal%3A/sites/default/files/image/image.jpeg"

No cigar, not even close. The new functions?

Url::fromUri()->toString() = "internal:/sites/default/files/image/image.jpeg"
Url::fromUri()->toUriString() = "base:sites/default/files/image/image.jpeg"

So, how to do it without doing it manually, of course? Removing internal: and prepending $base_url is very simple but still a hack.

2
  • You sure your first bit is right? normally an image stored in /sites/default/files/image/image.jpeg would have a uri of internal:/image/image.jpeg (So without the sites/default/files bit as well)
    – Leigh
    Commented Jun 8, 2018 at 9:45
  • Yes, I'm sure. The wording might not be perfect. It isn't an image widget but a link field that accepts an URL and is set to only accept internal references. That's what's inside, yes, and I can handle it everywhere else in twigs and similar with relative ease.
    – Gábor
    Commented Jun 8, 2018 at 10:06

1 Answer 1

1

Found it finally:

Url::fromUri($node->field_image->uri)->setAbsolute(TRUE)->toString()

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.