6

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}}

1 Answer 1

16

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()
    ->getStorage('file')
    ->loadByProperties(['uri' => $uri]);
  $file = reset($files);

  // if not create a file
  if (!$file) {
    $file = File::create([
      'uri' => $uri,
    ]);
    $file->save();
  }

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

  $node->save();
8
  • 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
    Commented Feb 1, 2017 at 8:26
  • 1
    I added a check if a file exists
    – 4uk4
    Commented Feb 1, 2017 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
    Commented Dec 19, 2017 at 0:08
  • 1
    how about if the image is coming from an external link. How do we save it inside Drupal? Commented Aug 27, 2018 at 6:46
  • 2
    @JohnReyTanquinco, use system_retrieve_file with managed set to TRUE to get $file.
    – 4uk4
    Commented Aug 27, 2018 at 7:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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