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

กติกาบาคาร่า (not verified)

กติกาบาคาร่าBest Casinos to Play Roulette for Real Money 2021

Thentaist (not verified)

viagra and alcoholic drinks password
viagra heartburn
tadalafil side effects long term
- safe pharmacy sites for viagra
[url=http://wtadalafil.com/#]canadian pharmacy online cialis
[/url] viagra 5 mg coupon e-mail address

คาสิโน (not verified)

คาสิโนPopular casinos

NAZA (not verified)

แฮนดิแคป Betting is the most return rate in betting.

zoom (not verified)

zoom
Easy to play on your phone without downloading. Moreover, there are more than 3,000 slot games that you can choose to spin the slots in minutes by minute. Don't miss out on world-class slots games Come and prove yourself today

mins (not verified)

123 Today's football price looks like an expert

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.[...]… Jorge Martin

seo (not verified)

Have you already setup a fan page on Facebook ?:–”, payment processing agent

mins (not verified)

123 เกม
Study the rules of playing online slots

seo (not verified)

Hi, i think that i saw you visited my website so i came to “return the favor”.I’m trying to find things to enhance my website!I suppose its ok to use a few of your ideas!! North American Bancard Agent

BryaneTwimb (not verified)

You actually expressed it perfectly.
https://topessaywritinglist.com/

BryaneTwimb (not verified)

Whoa a good deal of useful advice!
https://topessaywritinglist.com/

weackGtv (not verified)

online pharmacy busted [url=https://pharmacyhrn.com/ ]buy prescription drugs without doctor[/url] canadianpharmacyworld com

BryaneTwimb (not verified)

You suggested that fantastically.
https://topessaywritinglist.com/

uzair (not verified)

I do agree with all of the ideas you have presented in your post. They’re very convincing and will certainly work. Still, the posts are too short for starters. Could you please extend them a little from next time? Thanks for the post. poodles

Igoal (not verified)

IgoalWe are a provider of online gambling websites that will meet the full range of gamblers.

แทงบอลออนไลน์ (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.

เว็บคาสิโน (not verified)

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

Zaelwix (not verified)

fildena spam names
fildena in kuwait fildena
fildena 50 mg
- fildena information patients invitations
[url=https://fildenarxp.com/#]fildena 100mg
[/url] fildena prices canada login

Andy (not verified)

Jason Sudeikis’s character Kurt is a hard working man who has a very nice boss, whose tragic incident leaves the company in the hands of his bullying, cocaine-addicted son, played by Colin Farrell. 1v1.lol

weackAni (not verified)

canadian pharmacy viagra scam [url=https://pharmacyken.com/ ]canadian pharmacy testosterone cypionate[/url] proxy rx companion animal pharmacy

zoom (not verified)

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

Noah. (not verified)

This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. สลากกินแบ่งรัฐบาล

BryaneTwimb (not verified)

You stated it adequately.
https://topessaywritinglist.com/

BryaneTwimb (not verified)

You actually suggested that fantastically!
https://topessaywritinglist.com/

BryaneTwimb (not verified)

You reported that adequately.
https://topessaywritinglist.com/

Roman khan (not verified)

You made some good points there. I did a search on the topic and found most people will agree with your blog. คาสิโน

uzair (not verified)

As I website owner I conceive the content material here is rattling excellent , thanks for your efforts. techwear pants

seo (not verified)

You produced some decent points there. I looked on the internet for that issue and located most individuals goes along with along with your internet site. เว็บ123
You produced some decent points there. I looked on the internet for that issue and located most individuals goes along with along with your internet site. เว็บ123

Andy (not verified)

I don’t usually comment but I gotta state thanks for the post on this perfect one : D. blotting paper

Noah. (not verified)

Thank you so much as you have been willing to share information with us. We will forever admire all you have done here because you have made my work as easy as ABC. 메이저사이트

anus (not verified)

You made some good points there. I did a search on the topic and found most people will agree with your blog. Levinsohn's personal blog

anus (not verified)

Interesting post. I’ll be sticking around to hear much more from you guys. Thanks! articles about Ross Levinsohn

Roman khan (not verified)

After examine a couple of of the weblog posts on your web site now, and I really like your manner of blogging. I bookmarked it to my bookmark website record and will probably be checking back soon. Pls take a look at my web page as well and let me know what you think. कौन है Google का मालिक तथा यह किस देश की कंपनी है

Ziandal (not verified)

canadian pharmacy apcalis
prescription discount
welchol canadian pharmacy discount
- advocare pharmacy canada
[url=https://canadapharmacy-usa.com/#]canadian pharmacy discount codes
[/url] canada pharmacy online

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

เว็บพนันออนไลน์88
Easy to play on your phone without downloading. Moreover, there are more than 3,000 slot games that you can choose to spin the slots in minutes by minute. Don't miss out on world-class slots games Come and prove yourself today

123maxx (not verified)

Online football betting website All included here. Highly stable, able to bet on online football In the form of a tablet computer

แทงบอล

naza55 naza (not verified)

I procrastinate alot and by no means often go carried out. NAZA.

heng168 (not verified)

แฮนดิแคป Betting 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.

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

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

123maxx (not verified)

แฮนดิแคป At home or on vacation, it can also be Online football betting Anytime, anywhere

ราคาบอล (not verified)

ราคาบอล Read our bonus terms and conditions for Slots.

เว็บคาสิโน (not verified)

เว็บคาสิโน where can i buy cialis tadalafil in ipswich town

123PRO1 (not verified)

เว็บคาสิโน Online casinos Built to support people who want to play at a casino But unable to travel to the casino

zoom (not verified)

Game camps that offer games zoomIt is the number 1 hit game of the app. Anyone who likes to play slots games. You must not miss it, come and play at thezoom because it is a gambling camp With presentation The game comes in a new way

NAZA (not verified)

naza is a site for gambler

minx (not verified)

123 Sian formula works in casinos. Baccarat formula to make profit

สูตรรูเล็ต (not verified)

สูตรรูเล็ต
Classic online casino gambling games that can easily make money. And responds to the needs of the gambler as well สูตรรูเล็ต

NAZA (not verified)

แฮนดิแคป Recommend the best gambling website in them, this is really easy to play.

nnaza (not verified)

แฮนดิแคป will right away seize your rss feed as I can not in finding your e-mail subscription link or e-newsletter service.

Add new comment