Skip to main content

I was trying to create something quite simple.  How to get image file uri from media entity id or rendered entity. 

Or other variations you might have searched:

  • How to load existing media programmatically
  • How to get image file uri from media entity id
  • Call to a member function getFileUri() 
  • drupal File::load getFileUri 
  • drupal getFileUri

 

The steps to achieve this should be something like:

// get the file id
​​​​​​​$fid = $entity->field_icon->target_id;
// Load the image file.
$file = File::load($fid);
// Get URI of the image file.
$file_uri = $file->getFileUri();
// With the URI, generate a url for non-image style background image.
$image_path = file_url_transform_relative(file_create_url($file_uri));
// Create the twig variable to be used in the node.html.twig template file as the background image inline style.
$variables['background_image_url'] = $image_path;

The above code is correct.  However, the for me it was producing the following error

Error: Call to a member function getFileUri() on null

 

Solution

The solution to the getFileUri() error is as follows:

At the top of your file ensure that you have 

use Drupal\file\Entity\File;

use Drupal\file\FileInterface;

Then once you have returned the file load File::load($fid) – to do this the first use must exist in the file (use Drupal\file\Entity\File).  Then check that the output generated $file is an instance of FileInterface.  This can be completed by

if ($file instanceof FileInterface) {
//... code ...//
​​​​​​​}

Hence completing the second use – use Drupal\file\FileInterface

 

Related articles