How to attach an image or file to node in Drupal 8 programmatically

Posted by admin on Tue, 01/30/2018 - 09:09

Quick code sample on how to get and attach an image or file to node or other entity programmatically in Drupal 8.

Here's an example how you could save an image to node if you get this with file_get_contents

use \Drupal\node\Entity\Node;
 
// Create file object from remote URL.
$data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
$file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE);
 
// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
  ],
]);
$node->save();

If you have an image already exists in you file system - so you could just attach it without any additional file manipulation.

use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
 
// Create file object from a locally copied file.
$uri  = file_unmanaged_copy('public://source.jpg', 'public://destination.jpg', FILE_EXISTS_REPLACE);
$file = File::Create([
  'uri' => $uri,
]);
$file->save();
 
// Load existing node and attach file.
$node = Node::load(1);
$node->field_image->setValue([
  'target_id' => $file->id(),
]);
$node->save();

And special thanks to Drupal 8 developers - you could easily create an image placeholder!
Just like this:

use \Drupal\node\Entity\Node;
 
$node = Node::create([
  'type'  => 'article',
  'title' => 'Generated image test',
]);
$node->field_image->generateSampleItems();
$node->save();
×

Hey! Don't miss a new cool stuff!

Comments

Ken (not verified)

The function file_unmanaged_copy is deprecated in Drupal 8.7. How can you do this in Drupal 8.7?

shahmeerkhan (not verified)

Nice information, appreciate it in the author. It really is incomprehensible in my opinion now, but in general, the usefulness and significance makes my head spin. Many thanks and all the best! https://thetravelerseason.com/

Davidved (not verified)

camgirl girls stripping web cam ebony girls on cam.
model porn camming horny cam girls.
real nanny cam sex bestonlinesexcams1 ebony webcam sex.
webcam dog sex nursing home sex hidden cam high school hidden cam sex.
nude cam sites bbw cam sites cheapest cam site.
best adult webcam sites asian cam site teen web cam sites.

zeeshanarain (not verified)

This site is really a walk-through for all of the data you wanted about it and didn’t know who to ask. Glimpse here, and you’ll undoubtedly discover it. buy golden teachers mushroom online

smithseo (not verified)

hi, I’m having bad luck attempting to rank high for the keyword “victorias secret coupon codes”… PLEASE approve my comment!! https://royalcbd.com/product/cbd-gummies-10mg/

Add new comment