3

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

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();
  • 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
  • I added a check if a file exists – 4k4 Feb 1 '17 at 8:48
  • 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
  • how about if the image is coming from an external link. How do we save it inside Drupal? – John Rey Tanquinco Aug 27 '18 at 6:46
  • @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.