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

123abc (not verified)

เว็บ 123 We are happy to give advice to both new and old customers. There is a quality team to serve you 24 hours a day with a fast and automatic deposit and withdrawal system.

g2gwin8888 (not verified)

G2GWIN88 Office at a physical location in Poipet, Cambodia. There are numerous communication channels that can support emergencies 24 hours

igoal88 (not verified)

igoal88 Online casino sites With every bet A complete answer to the gambler.

igoal (not verified)

igoal Register for free online baccarat. You don't have to play baccarat in Poipet. Just go to the baccarat website

Naza1 (not verified)

เว็บพนันออนไลน์ Slots, Football, Lottery, Casino

fuu88 (not verified)

fuu88
We have strengths in diversity and fairness to our users. Online.

IGOAL88 (not verified)

IGOAL88
IGOAL88 is proud to be there to offer you fully regulated online soccer betting

bill (not verified)

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

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

เว็บพนันออนไลน์Whether you play through a computer, notebook or on a mobile phone, at Zoomm88 we support for all applications, both Android and IOS systems, clear HD images, all games, with quick deposit and withdrawal services for all banking systems. within 20 seconds only

เว็บ 123 (not verified)

เว็บ 123 The best online casinos in Thailand make good money.

zoom (not verified)

zoom Comprehensive online gambling website popular service the most in Thailand Accept all types of online sports betting and casinos.

boo (not verified)

web casino thailand.sa casino

III7X (not verified)

NAZA Easy to apply for membership, deposit 200, get an additional 100, free deposit-withdraw, no minimum, easy to play, modern auto system. Guarantee safety, betting on football, lottery, slots, complete

fun88 (not verified)

fun88
Betting sites do not have to go anywhere. Here, one stop

เว็บพนัน (not verified)

เว็บพนัน Popular online gambling websites that meet all the needs of gamblers.

DrakTot (not verified)

viagra 20mg pills log in
viagra with viagra
non prescription viagra
- viagra side effects
[url=http://withoutdctr.com/#]viagra online no prescription
[/url] viagra for daily use no prescription register

NAZA (not verified)

สูตรเซียน 1 online gambling website We have a friend referral system that can easily make money. For you, all customers, convenient to use and easy to do

ss (not verified)

กติกาบาคาร่า Anyone can play, really easy to play.

สูตรบาคาร่า (not verified)

สูตรบาคาร่า Can raise casino games into the online system, play anywhere, anytime.

Naza1 (not verified)

เทิร์นโอเวอร์ Slots, Football, Lottery, Casino

sa casino (not verified)

sa casino Online baccarat It's a hit game. There are rules that are not too difficult to understand.

bill (not verified)

เว็บแทงหวย Lotto is another betting that a lot of people in the world play and it been in this world for many many year

เว็บพนันออนไลน์ (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)

เว็บหวยออนไลน์ informative. I am going to watch

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

สูตรรูเล็ต The best online casinos in Thailand make good money.

naza (not verified)

naza The casino that has the most right now.

24 (not verified)

24
24 We are the service provider Online casinos With every bet A complete answer to the gambler

ไฮโล (not verified)

ไฮโล Online Sic Bo games are available on mobile phones. Easy to play for real money Service by a professional team.

yolo (not verified)

เกมสล็อต
Guaranteed by the service for a long time.

prednisolone effect (not verified)

how long does cialis last

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

Online football And online football betting websites That these gamblers use the service,
that is, is an online football betting website. The best in this era!
แฮนดิแคป

igoal88 (not verified)

igoal88 providers are guaranteed to give

naza (not verified)

เว็บคาสิโน will right away seize your rss feed as I can not in finding your e-mail subscription link or e-newsletter service.

thanunya (not verified)

คาสิโน Online gambling website that allows you to make great money And also allows you to bet 24 hours.

NAZA28 (not verified)

28 Online gambling website that allows you to make great money And also allows you to bet 24 hours.

wm casino (not verified)

If you’re interested in online gambling look no further, need to get started right here. wm casino

naza (not verified)

ไฮโล Lots of games, including many online slots betting games

yolo (not verified)

สูตรเซียน
Apply for membership through the staff 24 hours a day. Automatic deposit-withdrawal system.

thanunya (not verified)

NAZA The casino that has the most right now.

Iznajmljivanje ... (not verified)

Great post. Keep up with good work. Please book your vehicle here: Iznajmljivanje kombija Beograd

g2gwin8888 (not verified)

G2GWIN88 Office at a physical location in Poipet, Cambodia. There are numerous communication channels that can support emergencies 24 hours

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

แฮนดิแคป Today we will introduce Flaming Fox game.

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

เว็บพนันออนไลน์New style slots games that are played online And supports playing on both Android and ios mobile phones that are comfortable to play And also a play that does not limit the area to generate money Suitable for players in this age very much.

III7X (not verified)

NAZA Easy to apply for membership, deposit 200, get an additional 100, free deposit-withdraw, no minimum, easy to play, modern auto system. Guarantee safety, betting on football, lottery, slots, complete

MM79 (not verified)

ตารางบิงโก The best online gambling sites With every bet To meet all needs of the gambler with a complete range.

NAZA (not verified)

NAZA 1 online gambling website We have a friend referral system that can easily make money. For you, all customers, convenient to use and easy to do

เว็บนาซ่า (not verified)

เว็บนาซ่าWe review games every day to give you the best and widest

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

กติกา บาคาร่า is the website that have all the betting in it to answer all the needed for the gambler.

uzair (not verified)

cheers for posting this post. I am definitely tired of struggling to find relevant and intelligent commentary on this subject. Everyone nowadays seem to go to extremes to either drive home their viewpoint or suggest that everybody else in the globe is wrong. cheers for your concise and relevant insight. https://bridesingles.com/

chrisevan55 (not verified)

Nice weblog here! Also your site lots up fast! What host are you the use of? Can I get your affiliate link on your host? I want my website loaded up as quickly as yours lol 먹튀검증커뮤니티

Add new comment