Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victorpavlov/daca70fea44de7063dc5350d1d53aaeb to your computer and use it in GitHub Desktop.
Save victorpavlov/daca70fea44de7063dc5350d1d53aaeb 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());
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment