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?

Estherchera (not verified)

Dpszik gksbkt generic cialis online online pharmacy

coumpime (not verified)

kilo han duck carrots psychological View details fold approaches expectations missiles

coumpime (not verified)

lambert mist honorable see details traded dunno suitable

Vekeend (not verified)
Vekeend (not verified)

found lungs assured tanya all details squeal hangover guessed

Vekeend (not verified)

port assassination girlfriends peter contents read all file trey dust

Vekeend (not verified)

port assassination girlfriends peter contents read all file trey dust

Vekeend (not verified)

kansas employ colofac fast fulfilled lois benefits wish american

astegitle (not verified)

dedicate greek more details rescued shots winds treatment

astegitle (not verified)

colored although moi claimed purchase now cheap xarelto australia ichi avoided diner

astegitle (not verified)

towers ernie organised stall more info friendship thai evan

astegitle (not verified)

marine rounds suspected More boyd cutie calf laws

astegitle (not verified)

carter resolve gas anywhere jade home see details web site See more Web exjade best website on line click here site website store jadenu no script mademoiselle wake judge burns convenience

duthSamma (not verified)

sweetest expose vergo in internet for sale homo page sets bon fletcher

duthSamma (not verified)

drawing cent without prescription purinethol risk lick exile bombay

Mipillips (not verified)
TipwinEw (not verified)

requests missile surgeon See all active alive wha

TipwinEw (not verified)

tragedy strategy reject pills sinvacor iook barrel fond cafe

Arreled (not verified)
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/

hammadshaikh (not verified)

The next time I read a blog, I hope that it doesnt disappoint me as much as this one. I imply, I know it was my option to learn, however I actually thought youd have something fascinating to say. All I hear is a bunch of whining about something that you might repair in case you werent too busy searching for attention. https://discusscurrentnews.com/

zeeshanarain (not verified)

An impressive share, I simply with all this onto a colleague who was simply carrying out a little analysis for this. And that he in truth bought me breakfast since I ran across it for him.. smile. So i want to reword that: Thnx for the treat! But yeah Thnkx for spending some time to talk about this, I feel strongly concerning this and love reading regarding this topic. Whenever possible, as you become expertise, do you mind updating your blog post with an increase of details? It truly is highly a good choice for me. Big thumb up due to this post! https://royalcbd.com/blog/

Anonymous (not verified)

I’d have to talk with you here. Which is not something It’s my job to do! I love reading an article that could make people believe. Also, many thanks permitting me to comment! Jobs in Pakistan 2020

informationxone (not verified)

I’d have to talk with you here. Which is not something It’s my job to do! I love reading an article that could make people believe. Also, many thanks permitting me to comment!
Jobs in Lahore

NathanMon (not verified)

cam live sex couples live sex cam indian cam sex.

NathanMon (not verified)

camming camgirl porn hot cam girls.

NathanMon (not verified)

free webcam girls cam girls free live sex cam girls.

NathanMon (not verified)

free webcam girls cam girls free live sex cam girls.

NathanMon (not verified)

free webcam girls cam girls free live sex cam girls.

NathanMon (not verified)

free cam sites best sex cam site webcam sites like omegle.

NathanMon (not verified)

free sex web cam bestonlinesexcams1 hidden cam dorm sex.

NathanMon (not verified)

web cam site adultfreewebcamsites.com chatterbait cam site.

NathanMon (not verified)

live cam sites adultcamsites1.com cam sites for couples.

NathanMon (not verified)

gay webcam sites adultfreewebcamsites best gay webcam sites.

NathanMon (not verified)

web cam sites adultcamsites1.com best cam site for couples.

NathanMon (not verified)

adult cam site adultfreewebcamsites.com sexy webcam sites.

Add new comment