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

seo (not verified)

Hi there, I found your blog via Google while searching for first aid for a heart attack and your post looks very interesting for me. เว็บพนันออนไลน์

Anonymous (not verified)

It is always so nice and also packed with amusement for me and my office acquaintances to visit your site at the very least thrice weekly to read through the newest guidance you have. Baccarat Casino Match
It is always so nice and also packed with amusement for me and my office acquaintances to visit your site at the very least thrice weekly to read through the newest guidance you have. Baccarat Casino Match

titokf (not verified)

Here are some beautiful games that you can download for free from the Games City website
تحميل العاب
لعبة جاتا
لعبة gta vice city

iuytfg (not verified)

Here are some very special fighting and action games
لعبة gta san andreas
لعبة جاتا 10
لعبة ببجي

mueed Ahmed (not verified)

pretty practical stuff, overall I consider this is worth a bookmark, thanks Acabar Com a Ejaculação Precoce

anus (not verified)

I discovered your blog post internet site on google and appearance some of your early posts. Keep in the really good operate. I simply additional increase your Rss to my MSN News Reader. Seeking forward to reading far more from you finding out down the road!… Vrai et faux titre de séjour à vendre en ligne France

seo person (not verified)

when we are looking for apartment for rents, we usually choose those with very clean rooms” ดูหนังออนไลน์

uzair (not verified)

great points altogether, you simply received a logo reader. What could you suggest about your post that you made some days ago? Any positive? more info

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

The best online gambling sites With every bet To meet all needs of the gambler with a complete range แฮนดิแคป

bunny (not verified)

วิธีเล่นสล็อต Online gambling has been compiled in this website the best.

alex (not verified)

แฮนดิแคป The best football betting website, football betting website, the best online casinos supervised by experts and professional team.

Flaming Fox (not verified)

Flaming Fox The best online casino website in Thailand

naza (not verified)

Apply for <a href="https://naza55.net/">naza</a> the best online casino site. Easy to play, 100% not cheating.

88 (not verified)

88 Have fun and earn money with a comprehensive range of slots games and bets.

5678 (not verified)

กติกาบาคาร่า Fun gambling games make a lot of money

ไฮโล (not verified)

ไฮโล The most classic gambling that people around the world like to play Sic Bo game.

นาซ่า (not verified)

นาซ่า always you still decide to betting online, you may find the answer and having many questions. yes, you can. with that our website. thats provides services best super online betting game.

Noah. (not verified)

Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! click now

seo person (not verified)

The cast is hands-down the standout reason why this movie works. legacy knives

seo person (not verified)

Undeniably believe that which you said. Your favorite reason appeared to be on the net the simplest thing to be aware of. I say to you, I definitely get annoyed while people think about worries that they just don’t know about. You managed to hit the nail upon the top and also defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks ipvanish review

chrisevan55 (not verified)

dude this just inspired a post of my own, thanks idn poker

Roman khan (not verified)

I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz answer back as I’m looking to create my own blog and would like to know where u got this from. thanks Thiết bị y tế

seo person (not verified)

My spouse and i ended up being absolutely peaceful when Jordan managed to complete his studies from the ideas he made when using the blog. It’s not at all simplistic just to always be handing out procedures which often the rest might have been trying to sell. So we see we’ve got the writer to appreciate because of that. All of the explanations you’ve made, the easy site navigation, the friendships your site help foster – it’s all incredible, and it is leading our son in addition to the family feel that the situation is fun, and that is exceptionally indispensable. Thank you for the whole lot! pelisplis

muhammad AK (not verified)

Manchmal finden Sie das richtige Casino für sich. Mit dieser Website online blackjack fand ich einige der besten Online-Casinos gut bestellt. Sie bieten einige tolle Angebote.

seo (not verified)

I totally understand what you have explained. Actually, I browsed throughout your several other content articles and I do believe you are absolutely correct. Congrats with this particular blog. 스포츠토토먹튀

mueed Ahmed (not verified)

You made some decent points there. I seemed on the internet for the problem and found most people will associate with with your website. greek mythology adult

seo person (not verified)

when we are looking for apartment for rents, we usually choose those with very clean rooms” anime tv

Andy (not verified)

I just wanted to write down a quick comment to say thanks to you for all of the fantastic suggestions you are showing on this site. My time intensive internet look up has at the end been rewarded with useful points to talk about with my visitors. I would assume that most of us visitors actually are very much blessed to live in a fantastic network with many outstanding professionals with insightful strategies. I feel pretty grateful to have come across your entire web page and look forward to some more excellent moments reading here. Thanks a lot once more for everything. Beijing Soonercleaning Technology

Roman khan (not verified)

Black Ops Zombies… [...]some people still have not played this game. It’s hard to imagine or believe, but yes, some people are missing out on all of the fun.[...]… internet design

mueed Ahmed (not verified)

My spouse and i ended up being so more than happy Michael could conclude his investigations out of the ideas he obtained while using the weblog. It’s not at all simplistic to simply happen to be giving freely key points which often other people have been trying to sell. And we recognize we need you to thank for this. The specific illustrations you’ve made, the simple website navigation, the relationships your site assist to create – it’s all incredible, and it’s assisting our son and us consider that this matter is fun, which is truly vital. Thank you for the whole lot! where to buy gbl

Andy (not verified)

i signed up on clicksor last month and i was impressed with the amount of money i made in one month` Scraper API Coupon Code

seo person (not verified)

when we are looking for apartment for rents, we usually choose those with very clean rooms” buy high retention youtube views

seo (not verified)

Possible require all types of led tourdates with some other fancy car applications. Many also provide historic packs and other requires to order take into your lending center, and for a holiday in upstate New York. ??? local roofers near me

uzair (not verified)

Thanks for all your efforts that you have put in this. very interesting information. credit scores good

seo person (not verified)

Undeniably believe that which you said. Your favorite reason appeared to be on the net the simplest thing to be aware of. I say to you, I definitely get annoyed while people think about worries that they just don’t know about. You managed to hit the nail upon the top and also defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks Puremate air purifier

mahnoor faizan (not verified)

No doubt this is an excellent post I got a lot of knowledge after reading good luck. Theme of blog is excellent there is almost everything to read, Brilliant post. 123 free movies

seo person (not verified)

If this movie was a video game it would have actually been sweet, in fact the whole movie felt like the creators of this movie just played a whole bunch of video games with alien invasion and decided to make a movie of it by combining some aspects of those games. Best Foot Massager Uk

Andy (not verified)

I am pleased, I have to state. Really not often will i come across your blog which is every educative as well as enjoyable, and let me tell you, you have got strike the actual toenail about the head. The idea will be exceptional; the difficulty is something that doesn’t sufficient folks are speaking wisely about. I am extremely comfortable which i stumbled all through this kind of in my search for a very important factor relating to this. comprar aceite ecológico

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 promethazine

ghazanfar seo (not verified)

This is my first visit to your web journal! We are a group of volunteers and new activities in the same specialty. Website gave us helpful data to work. Indiana Fake ID

seo person (not verified)

when we are looking for apartment for rents, we usually choose those with very clean rooms” 먹튀검증

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

แฮนดิแคป It features mostly slots. However, there is also Blackjack, Roulette, Texas Poker, ...

เว็บพนันออนไลน์88 (not verified)

เว็บพนันออนไลน์88
Online gambling, football betting, casino, slots, lottery, we are the service provider. Complete online football betting, including many popular games, easy to play, automatic deposit and withdrawal system, 100% safe at zoom88.net

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

แฮนดิแคป Handicap football betting to make money

<a href="https:... (not verified)

Online casino NAZA7X, a complete online gambling website, open for service online casino for real money can play on mobile Bet as low as 10 baht only, deposit-withdraw, no minimum, 24 hours a day, and we also provide good service. Pay attention to customers in every detail, whether there is a problem with accessing the web. We are ready to serve.

igoal (not verified)

igoal levitra cooper http://uslevitraanna.com/ levitra blood pressure

chokde (not verified)

cialis side effects with alcohol bbsหวยออนไลน์

TT21 (not verified)

igoal Guide how to earn money from the casino website

NAZA28 (not verified)

NAZA New casino of thailand Ready to serve today.

บอลสเต็ป (not verified)

บอลสเต็ปA free bet is exactly as the name of that type of promotion implies

Add new comment