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

bunny bunny (not verified)

Online gambling website that has received the number 1 interest in Thailand, convenient in all aspects, whether it is slots, roulette, online lottery, football betting, baccarat, easy to use, excellent customer service.123

แฮนดิแคป (not verified)

A complete online gambling website in terms of casino games in particular แฮนดิแคป

123DD (not verified)

123 Online casinos It consists of Baccarat games, slots, card games, roulette and many other games.

Bill517 (not verified)

123 casino website that have all the betting in it to answer all the needed for the gambler

naza55 naza (not verified)

slot is just like you at the casino but In online. There everything like real casino ราคาบอลแฮนดิแคป

เว็บ123 (not verified)

Hello there, just became aware เว็บ123

heng168 (not verified)

แทงบอลเว็บไหนดี Music started playing anytime I opened this web site, so annoying!

seo (not verified)

Chaga mushroom coffee been recently brought to plenty of everything about simply because of the Ukrainian article author Alexandr Solzhenitsyn by it’s new ‘Cancer Ward’ in which traditional qualities is generally cured of a tumors on the help consume. Siberian Chaga stretch suit

yolo (not verified)

123 เกมThe best web Good for casino casino number1

yolo (not verified)

123 เกมThe best web Good for casino casino number1

naza (not verified)

ราคาบอลแฮนดิแคป paid easily through any smartphone.

123abc (not verified)

The best of betting games, baccarat, slots, roulette and many others that you can choose from, easy to use, available 24 hours a day.เว็บคาสิโน

minuu (not verified)

pg 123
It is a game camp with beautiful pictures, no jerk, is a camp that collects a lot of online slots.

Andy (not verified)

I found your article very thought provoking. The way it was written made me look at things from a different angle and think about what I originaly thought, why not visit us .I will definately be back again. buy steroids

uzair (not verified)

I hate the fact that my iPhone be changing words and shit like damn.. Let me be nonformal for a minute.|Ceezyyy| www.telenicosia.it

uzair (not verified)

I like what you guys are up also. Such clever work and reporting! Keep up the excellent works guys I’ve incorporated you guys to my blogroll. I think it will improve the value of my website . https://venture-lab.org/2021/best-vpns-for-netflix/

ghazanfar (not verified)

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. nu vaccine registration

chrisevan55 (not verified)

The the next time I read a weblog, I hope that this doesnt disappoint me up to this one. I am talking about, I know it was my substitute for read, but I just thought youd have something intriguing to state. All I hear is usually a few whining about something that you could fix should you werent too busy seeking attention. 꽁머니 공유

justin (not verified)

World Facts For Children… [...]here are some links to sites that we link to because we think they are worth visiting[...]… https://dynamichealthstaff.com/nurses-vacancy-in-kuwait

Abbasiseo Abbasiseo (not verified)

Awesome! I appreciate your contribution to this matter. It has been useful. my blog: how to impress a girl lovebirds for sale

Abbasiseo Abbasiseo (not verified)

I am not real superb with English but I come up this really easy to read . finches for sale

Mothymog (not verified)

osamelejsi brigher tomorrow stromectol
mattonata stromectol walgreens
buy stromectol 3mg
- is stromectol safe ?
[url=http://ivermectin-6mg.com/#]ivermectin 12mg pills
[/url] powiedziales should people with nervous disorders take stromectol

mueed Ahmed (not verified)

Rattling clean web site , appreciate it for this post. delta 8 gummies airport

seo person (not verified)

After study a few of the websites for your internet site now, and I genuinely as if your technique for blogging. I bookmarked it to my bookmark internet site list and will be checking back soon. Pls look at my website likewise and let me know what you think. dewapoker

seo person (not verified)

I am curious to find out what blog platform you are working with? I’m having some small security issues with my latest website and I would like to find something more safeguarded. Do you have any suggestions? dewapoker

anus (not verified)

european vacations are very exciting sepcially if you got to visit many places at once,, fitness equipment

anus (not verified)

hey there and thanks to your info – I’ve certainly picked up anything new from right here. I did however expertise a few technical issues the usage of this website, as I skilled to reload the web site a lot of instances prior to I may get it to load correctly. I had been puzzling over if your hosting is OK? No longer that I’m complaining, however sluggish loading instances instances will often have an effect on your placement in google and could injury your high-quality rating if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Well I am including this RSS to my e-mail and could look out for much more of your respective intriguing content. Make sure you replace this once more very soon.. fitness shop

uzair (not verified)

I hate the fact that my iPhone be changing words and shit like damn.. Let me be nonformal for a minute.|Ceezyyy| handgun training

uzair (not verified)

I like what you guys are up also. Such clever work and reporting! Keep up the excellent works guys I’ve incorporated you guys to my blogroll. I think it will improve the value of my website . top firearms training

ghazanfar (not verified)

It is a fantastic post – immense clear and easy to understand. I am also holding out for the sharks too that made me laugh. jansport big kid backpacks

เว็บ88 (not verified)

เว็บ88 call center service ready to solve problems and answer questions 24 hours a day

เกมไฮโล (not verified)

เกมไฮโลPlaying Sic Bo is another casino game that has been with our Thai society for a long time before there was online Sic Bo, which we often see playing. in a hard-to-reach area will be known only to the user group

123 (not verified)

123Roulette. Roulette. Table Games. Free play. Real Money.

เว็บ88 (not verified)

เว็บ88 The best of football betting here in one place

bunny bunny (not verified)

Online gambling website that has received the number 1 interest in Thailand, convenient in all aspects, whether it is slots, roulette, online lottery, football betting, baccarat, easy to use, excellent customer service.sa casino

Bill659 (not verified)

123 casino website that have all the betting in it to answer all the needed for the gambler

5678 (not verified)

A collection of many popular online betting games. That will make the gambler enjoy 123 เกม

123DD (not verified)

เว็บ 123 At home or on vacation, it can also be Online football betting Anytime, anywhere

ราคาบอลแฮนดิแคป (not verified)

ราคาบอลแฮนดิแคป There are many promotions with the benefit of participating in bets. สมัครเว็บ naza55
Best Online Casinos All of you can play online casino games at

naza55 naza (not verified)

Appreciate the recommendation. Will try it out. ราคาบอลแฮนดิแคป

แทงบอลเว็บไหนดี (not verified)

แทงบอลเว็บไหนดี Music started playing anytime I opened this web site, so annoying!

igoal88win.link (not verified)

Really easy to play, 100% not cheating.igoal88

yolo (not verified)
yolo (not verified)

pg 123
Where else can you find a better casino

naza (not verified)

ปั่นแปะ "Play in all types of casinos as
real casinos"

minb (not verified)

pg 123
There is a deposit-withdrawal system. Fast and automatic

ไฮโล (not verified)

naza ไฮโล Classic online casino gambling games that can easily make money

fuu88 (not verified)
naza55 naza (not verified)

นาซ่าI got what you mean ,bookmarked , very nice internet site .

chrisevan55 (not verified)

You created some decent points there. I looked over the internet for your problem and found most individuals should go coupled with with your internet site. tik tok video download

Add new comment