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

Mueed Ahmed (not verified)

Thanks so much for another post. I be able to get that kind of information information. friend, and exactly. [pii_email_09fefdd8c1cb3bccfeb6]

LazryNat (not verified)

toonen stromectol sante canada francais
kuchibiru stromectol dosage for head lice
order stromectol 3mg
- ivermectin covid
[url=http://stromectol-6mg.com/#]stromectol 6 mg
[/url] snames ivermectin for rabbit fur mites

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

igoal
Only the best online, live betting action. Come and place your bets now to beat the odds.

MM79 (not verified)

IgoalOnline gambling websites that meet the needs of gamblers

igoal88 (not verified)

igoal88 Deposit-withdrawal, fast, stable, excellent service

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

เว็บคาสิโนOur online casino platform makes it easy for everyone

IIOII (not verified)

นาซ่า Football betting, many casino games and the best, the most modern operating system Deposit - withdraw automatically 1 minute, bill cuts fast, automatic update web, not closed, update, disturbing customers.

ss (not verified)

You are my intake , I own few web logs and often run out from to brand : (.igoal88

bunny bunny (not verified)
เกมบิงโก (not verified)

We have a complete range of online casino legends. เกมบิงโก

Anonymous (not verified)

นาซ่า Register for free online baccarat. No need to play Baccarat Poipet, just enter the website and get real money at home. Baccarat online, Baccarat formula is very popular to make money.

Naza1 (not verified)

เว็บนาซ่า Casino, Football, Lottery, Slots

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

เว็บพนันออนไลน์ Web baccarat can be played on mobile phones anywhere, anytime.

เว็บ88 (not verified)

เว็บ88 Fish shooting game is considered a new online game of casino sites. Provides both fun and value from the points of the fish played and can be converted into real money. and can be withdrawn as you want

plam (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.เว็บ 123

ตารางบิงโก (not verified)

ตารางบิงโก Online gambling service providers That answers all needs Excellent gambler 24 hours a day

5678 (not verified)

ค่ายเกมสล็อต Lots of games, including many online slots betting games

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

You can make money through our website easily. Trial subscriptions and play here. เว็บพนันออนไลน์

123abc (not verified)

ค่ายเกมสล็อต Can raise the slot game into the online system, play anywhere, anytime

NAZA28 (not verified)

เว็บนาซ่า Betting on online casino is the best answer for the gambler.

bunny bunny (not verified)

best gambling website.เว็บคาสิโน

ปั่นแปะ (not verified)

ปั่นแปะ Online and online gambling in the most advanced form of gambling website in Thailand.

naza (not verified)
naza55 naza (not verified)

is famous for most people because can play when you free time ปั่นแปะ

NAZA (not verified)

เว็บคาสิโนออนไลน์ You don't have to look anywhere else, here, play games and earn real money.

เกมบิงโกIGOAL (not verified)

เกมบิงโกIGOAL
เกมบิงโก
is useful in support of my experience. thanks
admin

yolo (not verified)
sexy baccarat (not verified)

sexy baccarat cialis 5 mg coupon board index

28 (not verified)

28 Betting on online casino is the best answer for the gambler.

yolo (not verified)

เว็บคาสิโนออนไลน์
Number one in online gambling services casino

naza 55 (not verified)

Number one in online gambling services casinoเว็บคาสิโน

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

เว็บ123 Classic online casino gambling games that can easily make money. And responds to the needs of the gambler.

สล็อตออนไลน์ (not verified)

สล็อตออนไลน์ The best online casino website in Thailand

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

NAZA Number one in online gambling services casino

seo (not verified)

I appreciate your work , thanks for all the informative blog posts. พังงา ต้องรอด

seo person (not verified)

The cast is hands-down the standout reason why this movie works. Buy Juvederm Voluma Lidocaine

mahnoor faizan (not verified)

I learn some new stuff from it too, thanks for sharing your information. Harga koin Firo

Anonymous (not verified)

Marijuana has been classified as a schedule-1 drug. Despite this, research does not identify marijuana to have any habit-forming properties. In fact, the long-term effects of marijuana on the human body are still unidentified. Our Store - Buy Weed online

mahnoor faizan (not verified)

I have recently started a blog, the info you provide on this site has helped me greatly. Thanks for all of your time & work. HARD to IDR

Drankloh (not verified)

where to get generic cialis without prescription cialis super active 20mg 20mg cialis generic [url=https://regcialist.com/]cialis at a discount[/url] ’

brinsAni (not verified)

perscription drugs from canada rx specialty pharmacy canadian pharmacies vipps [url=https://inpharmxx.com/]Lanoxin[/url] ’

Drankloh (not verified)

brand cialis on line free samples of cialis cialis 20mg [url=https://regcialist.com/]where to buy cialis online for cheap[/url] ’

brinsAni (not verified)

canadian pharmacy near me zithromax online pharmacy rate online pharmacies [url=https://inpharmxx.com/]canadian pharcharmy onlinecanadian online pharmacy[/url] ’

uzair (not verified)

You created some decent points there. I looked on the internet for that issue and located most people may go along with with the site. BARS NEAR ME

seo person (not verified)

How can I attract more hits to my composing weblog? Rehab reviews Pennsylvania

uzair (not verified)

It is the best time to make some plans for the future and it’s time to be happy. I have learn this post and if I may just I wish to suggest you few interesting things or suggestions. Perhaps you can write subsequent articles regarding this article. I want to learn more things approximately it! 389sports

uzair (not verified)

Hey dude, what kind of wordpress theme are you using? i want it to use on my blog too .  texas88

faizan (not verified)

I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept. Thank you for the post. dental clinic

mahnoor faizan (not verified)

Cool stuff you have got and you keep update all of us. Wahroonga dental

seo person (not verified)

I’m new to your blog and i really appreciate the nice posts and great layout.;;*-” escor that u want to hire

Add new comment