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

<a href="http:/... (not verified)

Online gambling service providers That answers all needs Excellent gambler 24 hours a day.

MM79 (not verified)

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

bunny bunny (not verified)

กติกาบาคาร่า The best number 1 website in the country Complete convenience in online gambling services

เว็บ88 (not verified)

เว็บ88 Football betting, the most stable slot game with a best friend referral system.

Bill643 (not verified)

123 เกม casino website that have all the betting in it to answer all the needed for the gambler

123 เกม (not verified)

123 เกม
offers slot gaming for everyone. With many slot games on our floor

pg 123 (not verified)

pg 123 Safe and secure deposit-withdrawal system

5678 (not verified)

123 เกม A collection of many popular online betting games. That will make the gambler enjoy

88 (not verified)

88 Make a withdrawal transaction, no minimum (withdrawal 24 hours)

123pro1 (not verified)

pg 123 Online Slot Games It is a popular game that gamblers play all over the world. And is a game that many people have played

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

เว็บพนันออนไลน์ that collects many games in one place, whether it be Baccarat, Slots, Dragon Tiger. And various sports be it Football, basketball, tennis Or even E-sports, we have.

Naza1 (not verified)

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

fun88 (not verified)

fun88
Make a withdrawal transaction, no minimum (withdrawal 24 hours)

123abc (not verified)

You are able to capture several well guided adventures with assorted chauffeur driven car support. Many include important loan packages and some people is going to take someone for their depend toward the mortgage place, or a trip to upstate New York. baltimore limousine rentalsexy baccarat

igoal88 (not verified)

igoal88 The best online casino website in Thailand

naza55 naza (not verified)

ปั่นแปะAn online gambling service provider that meets international standards and meets all gambler needs.

naza (not verified)

ปั่นแปะ is a casino online

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

เว็บนาซ่า casino of thailand

123 (not verified)

cialis side effects with alcohol bbs 123

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

เกมบิงโก IGOAL
เกมบิงโก is the website that have all the betting in it to answer all the needed for the gambler

NAZA28 (not verified)

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

yolo (not verified)

dreamgaming
Where else can you find a better casino

naza55 naza (not verified)

You don't have to look anywhere else, here, play games and earn real money กติกาบาคาร่า

123PRO1 (not verified)

There are many different games to choose from. เว็บ123

Hustavbions (not verified)

skyvestaveny ivermectin cream over the counter
skratenie ivermectin dose for goats
stromectol 12mg
- brigher tomorrow stromectol
[url=http://stromectol3mg.com/#]stromectol
[/url] gira stromectol cost

seo person (not verified)

The cast is hands-down the standout reason why this movie works. Buy marijuana Hash Online UK

anus (not verified)

I’m impressed, I must say. Really rarely can i encounter a weblog that’s both educative and entertaining, and let me tell you, you have hit the nail for the head. Your idea is outstanding; the problem is something which there are not enough persons are speaking intelligently about. My business is very happy i found this around my search for something concerning this. dofollow backlinks

anus (not verified)

Glad to be one of several visitants on this awful website : D. casino pbn

anus (not verified)

Wazzup Fellow Writer, What you ?have here really have me interested up to the last word, and I wanna say to you I am not that typical man who finish the full length post of blogs as I most of the time got bored and tired of the trash content that is presented to me on a daily basis and I simply end up checking out the pics and maybe a headline, a paragraph and so on. But your headline and the first paragraphs were so cool and it right on the spot got me hooked. Thanks for tearing me out of this boring world! Thanks, really. link building for seo

anus (not verified)

I recently came across your blog and have been reading along. I thought I could leave my first comment. I don’t know what to say except that I have enjoyed reading what you all have to say best backlinks for seo

anus (not verified)

I was reading some of your content on this website and I believe this site is rattling instructive! Retain putting up. manual backlinks

Laim (not verified)

Can I say that of a relief to locate somebody who in fact knows what theyre dealing with online. You definitely discover how to bring a worry to light and make it crucial. Lots more people must check this out and see why side on the story. I cant believe youre no more well-liked when you undoubtedly provide the gift. http://forms-int.dmacc.edu/public/Lists/LegalCommSurvey/DispForm.aspx?ID=1901

justin (not verified)

Your blog is one of the better blogs I’ve came across in months. Thank you for your posts and all the best with your work and blog. Looking forward to reading new entries! www.onohosting.com

uzair (not verified)

In today's active world, sports have become more and more popular. With this popularity comes the need to have collections of memorabilia to remind us of those sporting events and heroes. The collectible sports memorabilia industry is thriving and growing with this popularity in modern sports such as basketball, baseball, football, golf, and NASCAR. 안전놀이터

anus (not verified)

I rather take a ? in an out house on a hot day at a baseball game before I put my personal problems on Fb or twitter lol|Ayengel| เครื่องมือสร้างลิงค์

anus (not verified)

Hi, if you want to get higher rankings, you should check out the plugin I left in my link, it will help. ผู้เชี่ยวชาญด้านการสร้างลิงค์

ica panorama (not verified)

Wow great post! Thankyou for sharing the information, its very helpful. jasa fotografi

anus (not verified)

You, my pal, ROCK! I found just the information I already searched all over the place and just could not locate it. What a perfect web site. ลิงก์ย้อนกลับจำนวนมาก

anus (not verified)

There are a handful of intriguing points at some point in this posting but I don’t determine if I see these center to heart. There exists some validity but Let me take hold opinion until I take a look at it further. Excellent write-up , thanks and we want a lot more! Combined with FeedBurner too การตลาดดิจิทัล

anus (not verified)

Spot on with this write-up, I actually suppose this website needs far more consideration. I’ll most likely be once more to read much more, thanks for that info. การตลาดดิจิทัล

seo (not verified)

Hi there! Nice stuff, please do tell me when you finally post something like this! 야맵

seo (not verified)

Rattling clean internet site , thanks for this post. พังงา ต้องรอด

chrisevan55 (not verified)

I was rattling happy to find this site on bing, just what I was searching for : D likewise bookmarked . https://baysidetechnology.com.au/

ghazanfar (not verified)

Love to read it,Waiting For More new Update and I Already Read your Recent Post its Great Thanks. เว็บพนันออนไลน์ เว็บตรงไม่ผ่านเอเย่นต์

seo (not verified)

Rattling clean internet site , thanks for this post. ที่เที่ยวกระบี่

Roman khan (not verified)

I agree with your thought. Thank you for your sharing. 토토사이트 포르쉐

uzair (not verified)

I haven’t checked in here for a while since I thought it was getting boring, but the last several posts are good quality so I guess I will add you back to my everyday bloglist. You deserve it friend 토토사이트 major

Roman khan (not verified)

I’m curious to find out what blog platform you have been utilizing? I’m experiencing some minor security issues with my latest site and I’d like to find something more secure. Do you have any recommendations? 토토사이트 턱시도

Roman khan (not verified)

a little something written here was absolutely Lots of great . an incredible I just want 심바 먹튀검증

Roman khan (not verified)

glass dining tables will always be the best design and option that i would choose for our dining room” 파워볼 가족방

Add new comment