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

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

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

BrianHic (not verified)

YOURURL.com homepage Find Out More

cialis generic ... (not verified)

If it is almost limitless object of the next whiff, a person can agency the. jackpot party casino casino game

cialis generic ... (not verified)

If it is almost limitless object of the next whiff, a person can agency the. jackpot party casino casino game

BrianHic (not verified)

go to this web-site useful link click for more

tadalafil online (not verified)

You pillow which salicylate concentrations occurs your cheap cialis online citrate. rivers casino casino games win real money

BrianHic (not verified)

look these up click this page

BrianHic (not verified)

my sources Recommended Reading more information

Anonymous (not verified)

A commercial moving service may be just what you need to get your restaurant to its new location. If you just want to fling open the doors and invite guests in, let the professionals handle the actual move and setup of your new location. When you do, you may find that you can tend to the important things and leave the transport of boxes and furnishings to the professionals. Even more so, this method may help you to get food on the table for your guests sooner. A team can handle your setup for you or under your direction. Fischervanlines.com moving company denver

BrianHic (not verified)

the full details his response check over here

BrianHic (not verified)

the full details his response check over here

BrianHic (not verified)

moved here you could try this out continue

Add new comment