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

สมัครเว็บ123 (not verified)

สมัครเว็บ123 Hello there, just became aware of your blog through Google, and found that it’s really informative

บอลไหล (not verified)

Online football betting In this age it is very easy to do. And gamblers around the world turned Online football betting บอลไหล

zoom (not verified)

zoom

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

casino online (not verified)

casino online Gambling that has been popular for many years. Casino deposit Via online channels at

john orton (not verified)

NAZA 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.

คาสิโนออนไลน์ (not verified)

คาสิโนออนไลน์.Many online betting game centers are avaliable on here. Bring it on.

Andy (not verified)

Thanks for the points shared using your blog. Something else I would like to talk about is that weight reduction is not information about going on a dietary fad and trying to reduce as much weight that you can in a set period of time. The most effective way to burn fat is by having it slowly and gradually and obeying some basic ideas which can assist you to make the most from your attempt to shed weight. You may realize and already be following a few of these tips, nevertheless reinforcing knowledge never does any damage. best friend instagram caption

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

บอลสเต็ป
The best online football betting website and has a form of football betting that can meet the needs of the gambler in its entirety บอลสเต็ป

Abbasiseo Abbasiseo (not verified)

great work… Excellent weblog here! Also your web site a lot up fast! What web host are you the usage of? Can I get your associate link on your host? I want my website loaded up as fast as yours lol… best quotes of whatsapp

minv (not verified)

เกม123
Live casino games are channels for betting on games. Online casinos

UFA (not verified)

A good casino website that answers Player deposit and withdrawal, no UFA

arm168 (not verified)

A collection of casino games Complete online formUFA

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

<a href="http://www.zoom88.net/"><b>เว็บพนันออนไลน์</b></a> Online gambling sites that everyone should try the most right now. Easy to play for real money

arm168 (not verified)

Online gambling sites with more than 10,000 people actually accessing it every day.เว็บ 123

Andy (not verified)

Hi there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this page to him. Pretty sure he will have a good read. Thanks for sharing! Travel quotes for Instagram

Mueed Ahmed (not verified)

I would like to consider the ability of thanking you for that professional guidance I have often enjoyed checking out your site. I’m looking forward to the particular commencement of my college research and the entire prep would never have been complete without dropping by your site. If I may be of any assistance to others, I’d personally be glad to help as a result of what I have gained from here. Los Angeles

Mueed Ahmed (not verified)

I am glad that it turned out so well and I hope it will continue in the future because it is so worthwhile and meaningful to the community. Downtown LA Juice Bar

justin (not verified)

When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four e-mails with the same comment. Is there any way you can remove people from that service? Many thanks! 안전놀이터

Bbshmodo (not verified)

pills like viagra https://loxviagra.com/ viagra usage

Andy (not verified)

Greetings, have you ever before wondered to write regarding Nintendo Dsi handheld? CBD

Jebgweack (not verified)

Myambutol http://pharmacylo.com/ Dipyridamole

Gtnbamaps (not verified)

vietnamese viagra 5 foods [url=http://jokviagra.com/ ]viagra heart attack[/url] best herbal viagra

RebfReest (not verified)

cialis without prescription http://rcialisgl.com/ cialis with dapoxetine 80mg

Gtnbamaps (not verified)

mandy flores viagra https://jokviagra.com/ what is viagra pills

seo (not verified)

I am glad that it turned out so well and I hope it will continue in the future because it is so worthwhile and meaningful to the community. 꽁머니홍보방

Anooweack (not verified)

viagra availability in karachi [url=http://llviagra.com/ ]handel viagra strafbar[/url] viagra rezeptfrei tschechien

DrewKet (not verified)

md pharmacy online viagra
can trinitrate be taken with viagra
sildenafil without prescription
- viagra and viagra purchase online
[url=http://nodoctprescript.com/#]viagra without doctor
[/url] what side effects do you get when taking viagra 20mgm with warfarin and digoxin

uzair (not verified)

My friend sent me here and I thought I’d say hi, great blog. สมัครบาคาร่า

uzair (not verified)

I’m not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back down the road. Cheers https aka ms remoteconnect microsoft

Jebgweack (not verified)

best 10 online canadian pharmacies http://pharmacylo.com/ online canadian pharcharmy

alex (not verified)

The facts on your blog site is seriously informative and good, it served me to clear up my problem and responses are also handy. Men you can go by means of this blog site and it helps you a ton. art of writing

LbsoReest (not verified)

cialis viagra levitra samples [url=http://ucialisdas.com/ ]generic cialis cipla[/url] О±П…ОёОµОЅП„О№ОєОї П‡О±ПЂО№ cialis

Andy (not verified)

Music started playing anytime I opened this web site, so annoying! buy fake money online

seo (not verified)

You got a really useful blog. I have been here reading for about an hour. I am a newbie and your success is very much an inspiration for me. buy fake money online

Lebnweack (not verified)

dapoxetine https://xlnpharmacy.com/ trusted canadian pharmacy

uzair (not verified)

As a Newbie, I am continuously exploring online for articles that can help me. Thank you Lisbon markets

Mueed Ahmed (not verified)

A cool article at that time partner ! Regards for that article . Private Villas

anus (not verified)

Where may I get a hold of this page layout? Seattle Must See

seo (not verified)

I am glad that it turned out so well and I hope it will continue in the future because it is so worthwhile and meaningful to the community. 먹튀검증사이트

Bbshmodo (not verified)

reddit viagra [url=https://loxviagra.com/ ]viagra strengths[/url] buy viagra online amazon

RebfReest (not verified)

black ants cialis australia [url=http://rcialisgl.com/ ]where to buy cialis soft tabs[/url] cialis southafrica

RebfReest (not verified)

cialis/generic http://rcialisgl.com/ cialis generic

คาสิโน (not verified)

คาสิโน Best Online Casinos and Slots Sites The Best Payout Gambling Sites for Real Money Play

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

เว็บพนันออนไลน์ 88

is the website slot casino that have all the betting in it to answer all the needed for the gambler. Betting in Soccer is the most return rate in betting. You can bet in any team that you want to bet. Also, it real live time betting so you cannot miss this bet at all, I gaurantee you.

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

NAZA.It has all the online bets you want to play. There are many promotions with benefits to participate. Play through any smartphone, complete, convenient, our website.

heng168 (not verified)

คาสิโน betting In this age it's very easy to do. betting coz it is convenient can stay home or go on a trip betting anytime.

คาสิโน (not verified)

คาสิโน
คาสิโน The best online gambling sites With every bet To meet all needs of the gambler with a complete range

123maxx (not verified)

Anyone can play, really easy to play.
Finally there is entertainment in your spare time, there are over 100 games to choose from.สมัครเว็บ123

LbsoReest (not verified)

comprar cialis online http://ucialisdas.com/ cialis prices walmart

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

บอลสเต็ป Only the best online, live betting action. Come and place your bets now to beat the odds.

Add new comment