I am trying to update a node image field programmatically. I currently loading the node like this:

$node = Node::Load(1);

have the URI if the image that I want to set. I have tried this but no luck:

$node->set('field_image_head', array('#uri' => $imageUri));
  1. How do I now update the node image with an image URI?
  2. The twig will need to get the URL from the image field like so
    {{ file_url(node.field_image_head.entity.fileuri}}

You have to create a file for the image first before you can add it to the node.

use Drupal\node\Entity\Node;
use Drupal\file\Entity\File;

  $node = Node::load(1);
  $uri = 'public://image.jpg';

  // check first if the file exists for the uri    
  $files = \Drupal::entityTypeManager()
    ->loadByProperties(['uri' => $uri]);
  $file = reset($files);

  // if not create a file
  if (!$file) {
    $file = File::create([
      'uri' => $uri,

  $node->field_image[] = [
    'target_id' => $file->id(),
    'alt' => 'Alt text',
    'title' => 'Title',

  • 1
    The file is already created I think. It's the default image uploaded in content type. I have got the URI of the default image and want to set that. Would I still need to create a file for it? @4k4
    – harnamc
    Feb 1 '17 at 8:26
  • 1
    I added a check if a file exists
    – 4k4
    Feb 1 '17 at 8:48
  • 1
    You should create your file and then call the save method in two separate statements. As written, $file would be the Boolean returned by the save method.
    – Chance G
    Dec 19 '17 at 0:08
  • 1
    how about if the image is coming from an external link. How do we save it inside Drupal? Aug 27 '18 at 6:46
  • 2
    @JohnReyTanquinco, use system_retrieve_file with managed set to TRUE to get $file.
    – 4k4
    Aug 27 '18 at 7:37

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.