Skip to content

Instantly share code, notes, and snippets.

@schnippy
Last active April 24, 2024 19:13
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save schnippy/34e134264ea356bf6c23ff6127ccc5d0 to your computer and use it in GitHub Desktop.
Save schnippy/34e134264ea356bf6c23ff6127ccc5d0 to your computer and use it in GitHub Desktop.
Programmatically get file URL from a media entity entity reference field in Drupal 8

Programmatically get file URL from a media entity reference field in Drupal 8

I have a content type with a media (image) entity reference field (field_thumbnail_image) and I want to grab its file URL. For this, I need to load the media entity, isolate its source object using getSource, then load this source as a file entity so I can make a proper URL.

    // load the media entity from the media entity reference field
    $media_entity = Media::load($entity->field_thumbnail_image->target_id);

    // get the file source value for the media entity
    $source_value = $media_entity->getSource()->getSourceFieldValue($media_entity);

    // if a file resource exists, then build an image_style url based off of it using the image_style 'thumbnail'
    if ($source_value) {
      $file_entity = File::load($source_value);
      $media_url = ImageStyle::load('thumbnail')->buildUrl($file_entity->getFileUri());
    }
@leymannx
Copy link

leymannx commented Dec 3, 2021

Nice! Thank you 🙏

Another one to get just the file URL using the \Drupal::service('file_url_generator')->generateAbsoluteString($uri) service:

$image_uri = $node->field_my_media_field->entity->field_media_image->entity->getFileUri();
$image_url = \Drupal::service('file_url_generator')->generateAbsoluteString($image_uri);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment