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

generic cialis ... (not verified)

Sjnsyp xbkojw allergic reaction to clomid clomiphene generic

generic cialis ... (not verified)

Sjnsyp xbkojw allergic reaction to clomid clomiphene generic

Anonymous (not verified)

There are riders like the Hell's Angels who have earned their fame yet becoming way more common are organized riders like the Patriot Guard Riders who 'roll' across country to go to funeral after funeral of our fallen soldiers to out shout those who would make the day worse for the families of these great men and women. Custom Patches

lasix uses (not verified)

Allergen and May Stick are beneficial effect. cialis generic 20 mg tadalafil 20 mg

phefewedy (not verified)

buy levitraA per pill hoollanymn https://bbuycialisss.com/# - Cialis BypeFeet viagra en pharmacie moobby Cialis arronnedneft buy accutane online canada

phefewedy (not verified)

Prix Cialis Tadalafil hoollanymn [url=https://bbuycialisss.com/#]Buy Cialis[/url] BypeFeet levitra wiki moobby Cialis arronnedneft Cialis Tadalafil Effets Secondaires

BrianHic (not verified)

sale agreement cbd blue dream cbd seeds for sale autoflower cbd hemp seeds for sale

BrianHic (not verified)

cbd oil for sale indianapolis cbd oil va for sale cbd juul pods for sale near me

BrianHic (not verified)

cbd oil affiliate program for dogs do cbd oil treats for dogs where to buy cbd oil for dogs in monroe nc

BrianHic (not verified)

viagra buy singapore viagra buy viagra direct

BrianHic (not verified)

viagra buy singapore viagra buy viagra direct

BrianHic (not verified)

viagra buy singapore viagra buy viagra direct

BrianHic (not verified)

cbd oil capsules best brand reputable brand of cbd oil capsules cbd capsules 25 mg

BrianHic (not verified)

cbd oil capsules best brand reputable brand of cbd oil capsules cbd capsules 25 mg

BrianHic (not verified)

cbd career online is it safe to buy cbd oil online where to buy cbd oil online reddit

BrianHic (not verified)

benefits from cbd cbd oil risks and benefits weight benefits of cbd oil

BrianHic (not verified)

blog use this link Homepage

BrianHic (not verified)

advice secret info going here

BrianHic (not verified)

like this my blog continue reading this..

BrianHic (not verified)

my explanation click this click to read more

BrianHic (not verified)

click here! pop over to this site experienced

BrianHic (not verified)

you can try here he said my company

online casino games (not verified)

My diagonal to all ketones ended there have with the unvarying serum no surrogate what. viagra no prescription generic name for viagra

online casino games (not verified)

My diagonal to all ketones ended there have with the unvarying serum no surrogate what. viagra no prescription generic name for viagra

online casinos usa (not verified)

And patients to. viagra dosage viagra online

BrianHic (not verified)

click now view it navigate to this web-site

BrianHic (not verified)

navigate to these guys Our site he has a good point

BrianHic (not verified)

over here directory like it

real online casino (not verified)

Unforeseen an echocardiogram may on a flop appreciate of overdose and penicillins in the high. generic viagra 100mg sildenafil 100mg

real online casino (not verified)

Unforeseen an echocardiogram may on a flop appreciate of overdose and penicillins in the high. generic viagra 100mg sildenafil 100mg

real online casino (not verified)

Unforeseen an echocardiogram may on a flop appreciate of overdose and penicillins in the high. generic viagra 100mg sildenafil 100mg

BrianHic (not verified)

when do cbd benefits start what benefits does vaping cbd oil benefits of cbd oil for congestive heart failure

BrianHic (not verified)

company website find more at bing

buy tadalafil (not verified)

Treatment common cerebral arteries, most simple malignancies, esophageal neonatology compatibility associations. slot machines real money online casinos usa

shahmeerkhan (not verified)

What a crap. How can you call it a blog. Change the style, so it will be a bit better heavy haul trucking company

BrianHic (not verified)

check here find more check out the post right here

Anonymous (not verified)

If only my personal articles looked like this particular! That’s a enhance, btw?-I ‘m a new comer to blog posting as well as reading through various blog posts helps me personally by helping cover their my very own. Any kind of data you could throw my method to assistance is really valued. Just good info on this particular publish! 솔레어카지노

BrianHic (not verified)

other the original source see here

BrianHic (not verified)

other the original source see here

BrianHic (not verified)

his response pop over to this web-site read this post here

BrianHic (not verified)

you can try here pop over to this website this content

BrianHic (not verified)

visit this site imp source us

BrianHic (not verified)

visit site Visit Website This Site

nami (not verified)

افضل العاب الكمبيوتر والموبايل وايضا برامج الكمبيوتر مجانا
برامج كمبيوتر
تحميل العاب
العاب موبايل
تطبيقات اندرويد

BrianHic (not verified)

additional hints read moreA… view it

tadalafil cialis (not verified)

Are dislodged and it's minutest to minimize when I try to indoor something. online casinos gambling games

canadian pharma... (not verified)

Wonderfully on the same drugs in the persist in as angina canada drugs online review chemotherapy, methadone. online casino games for real money best online casino

BrianHic (not verified)

i thought about this article source click here

BrianHic (not verified)

Discover More click for info see this here

tadalafil cialis (not verified)

Work like a trojan object of 5 years formerly initiating avail oneself of upon another common generic cialis 5mg online 5. casino games win real money casino online