0

I have a File entity loaded programmatically. I want to load a Media entity from it. Is there a way to achieve this?

2
  • Do you mean you want to load the Media entity the File entity belongs to? Or you want to create a new Media entity and add the File entity you've created to that File entity?
    – Jaypan
    Commented Apr 6, 2020 at 16:16
  • Yes exactly i want to load the Media entity the File belongs to.
    – lchabrand
    Commented Apr 6, 2020 at 16:24

2 Answers 2

5

Example - if your File entity is loaded in a variable named $file, and the field name on the Media entity is field_media_image:

$media_entities = \Drupal::entityTypeManager()->getStorage('media')->loadByProperties([
  'field_media_image' => $file->id(),
]);

$media_entity = is_array($media_entities) ? array_pop($media_entities) : NULL;

Note1 : If the File object belongs to more than a single Media entity, you will need to loop through $media_entities to find the one you want.

Note 2: $media_entity will either contain the Media entity the File entity belongs to, or be NULL if the File entity doesn't belong to a Media entity.

1

Actually i found a good answer, i used :

$result = \Drupal::service('file.usage')->listUsage($file);

and then in the $result i am checking if any keys called media exist. If so, i can then load my Media :)

1
  • 1
    There is an API for doing what you want, where you don't have to do the same checks you noted. Please see my answer to this question.
    – Jaypan
    Commented Apr 6, 2020 at 17:53

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.