I have a File entity loaded programmatically. I want to load a Media entity from it. Is there a way to achieve this?
-
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?– JaypanCommented Apr 6, 2020 at 16:16
-
Yes exactly i want to load the Media entity the File belongs to.– lchabrandCommented Apr 6, 2020 at 16:24
2 Answers
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.
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 :)
-
1There 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.– JaypanCommented Apr 6, 2020 at 17:53