Last active
May 26, 2022 18:46
-
-
Save paboden/3723d2be0dd455406b3d4b68fa0ea259 to your computer and use it in GitHub Desktop.
Drupal 8/9: Get the URL of any file inside of a media reference, in any entity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Use this snippet to get the original URL of images, and the direct file URL of other media types (like documents and videos). | |
| $entity_type_manager = \Drupal::entityTypeManager(); | |
| $media_manager = $entity_type_manager->getStorage('media'); | |
| $file_manager = $entity_type_manager->getStorage('file'); | |
| $generator_service = \Drupal::service('file_url_generator'); | |
| $urls = []; | |
| // If the entity has the media reference field in question. | |
| if ($entity_with_media_reference_field->hasField('MEDIA_REFERENCE_FIELD_NAME')) { | |
| foreach ($entity_with_media_reference_field->get('MEDIA_REFERENCE_FIELD_NAME')->getValue() as $delta => $item) { | |
| // If a media item is returned (field isn't empty). | |
| if ($media_item = $media_manager->load($item['target_id'])) { | |
| // Get the file id and load up the file entity. Then get the file URI. | |
| $file = $media_item->get('field_media_file')->getValue(); | |
| $file_uri = $file_manager->load($file[0]['target_id'])->getFileUri(); | |
| // Get the URL string from the URI information. This is original URL, NOT an image style url. | |
| $urls[] = $generator_service->generateString($file_uri); | |
| }; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment