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

Andrew Fletcher04 Apr 2025
Managing .gitignore changes
When working with Git, the .gitignore file plays a critical role in controlling which files and folders are tracked by version control. Yet, many developers are unsure when changes to .gitignore take effect and how to manage files that are already being tracked. This uncertainty can lead to...
Andrew Fletcher26 Mar 2025
How to fix the ‘Undefined function t’ error in Drupal 10 or 11 code
Upgrading to Drupal 10.4+ you might have noticed a warning in their code editor stating “Undefined function ‘t’”. While Drupal’s `t()` function remains valid in procedural code, some language analysis tools — such as Intelephense — do not automatically recognise Drupal’s global functions. This...
Andrew Fletcher17 Mar 2025
Upgrading to PHP 8.4 challenges with Drupal contrib modules
The upgrade from PHP 8.3.14 to PHP 8.4.4 presents challenges for Drupal 10.4 websites, particularly when dealing with contributed modules. While Drupal core operates seamlessly, various contrib modules have not yet been updated to accommodate changes introduced in PHP 8.4.x. This has resulted in...