4

I have the file ID (fid), and the rest of the file object.

I need to get fields from the parent media entity, but I can't find anything about loading a media entity from a file object.

Drupal 8.4.0

Update

I asked this question in relation to another: Media name as link to file

As far as I could find Kevin's comment is correct.

4
  • The File object won't have a reference to a Media entity using it. You need to load the Media entity and access the file that way.
    – Kevin
    Nov 11 '17 at 0:15
  • Just realised I didn't say what version of Drupal I'm on. @Kevin, it that for D8? Nov 13 '17 at 9:57
  • 1
    Wouldn't a file entity be related to a media entity via an entity reference field? And doesn't core have reverse entity reference field logic built-in? Feels like you should be able to get that pretty easily
    – Clive
    Nov 15 '17 at 14:25
  • @Clive, exactly my thoughts, I guess it's that logic I'm asking about. Nov 15 '17 at 14:57
4

Using the service file.uses you get the file media object:

Example:

$file is a loaded file object.
$file = \Drupal::entityTypeManager()->getStorage('file')->load($fid)
$result = \Drupal::service('file.usage')->listUsage($file);

$result should now contain an array like so:

$result['file']['media']['4372'] = 2;

Where 4372 is the media id. and 2 the times the file is used.

From the docs of listUsage:

@return array
   *   A nested array with usage data. The first level is keyed by module name,
   *   the second by object type and the third by the object id. The value of
   *   the third level contains the usage count.
1

I recently needed to do the same, and came up with the following. First, load the file entity from the fid:

$fid = 1000;
$file = \Drupal\file\Entity\File::load($fid);

Then, call file_get_file_references on the file entity:

$references = file_get_file_references($file);

Per the docs, you will get back a nested array of the referencing field names, entity types, entity ids, and finally the referencing entity itself.

0
use Drupal\media\Entity\Media;
use Drupal\node\Entity\Node;

function myFunction() {
  $node_load = Node::load($nids);
  $media_field = $node_load->get('media_field_machine_name')->getString();
  $media_entity_load = Media::load($media_field); 
  $uri = $media_entity_load->field_media_video_file->entity->getFileUri(); 
  $banner_media_url = file_create_url($uri);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.