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

naza55 naza (not verified)

Meet Paying Slots at the Most Popular Casinos in Thailan NAZA.

Bill1267 (not verified)

แฮนดิแคป Soccer bet is the most common bet and most worldwide because it pretty easy to bet and get a lot of money from it

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

The best online gambling sites With every bet To meet all needs of the gambler with a complete range แฮนดิแคป

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

naza (not verified)

Apply for naza the best online casino site.

123maxx (not verified)

แฮนดิแคป Good luck belongs to you throughout your investment.

88 (not verified)

88 Forget the old-fashioned casinos. Here you will find a new type of casino that will make you enjoy all kinds of betting.

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

บอลสเต็ป proud to be there to offer you fully regulated online soccer betting

ไฮโล (not verified)
ไฮโล (not verified)

ไฮโลIt is a game that these online gamblers are most popular today. Why do most people choose to play baccarat online? Because it is a game that can make money and finish the game quickly, you don't have to wait too long, you can already make a huge profit

NAZA (not verified)

NAZA NAZA web, we have services that are international standards. and fast

NAZA (not verified)

this's a site for gambler. naza

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

เว็บคาสิโน Hello there, just became aware of you

minv (not verified)

pg 123

Comes with a new system In a modern, secure online casino web system.

Abbasiseo Abbasiseo (not verified)

Chaga mushroom coffee been recently brought to plenty of everything about simply because of the Ukrainian article author Alexandr Solzhenitsyn by it’s new ‘Cancer Ward’ in which traditional qualities is generally cured of a tumors on the help consume. Siberian Chaga 올인구조대

naza55 naza (not verified)

Online casinos Baccarat online for real money free trial play แฮนดิแคป

yolo (not verified)

แฮนดิแคป
Good luck belongs to you throughout your investment.

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

กติกาบาคาร่า
The most popular gambling game of people around the world. And make a lot of money กติกาบาคาร่า

NAZA (not verified)

นาซ่า Gather the hottest promotions That appeals to all investors

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

กติกาบาคาร่า Online casino sites that offer baccarat betting games that can meet the needs of the gambler as well. And there are many online gambling games available to complete gambling.

ไฮโล (not verified)

ไฮโล You can easily earn money through refer a friend system on our website. Become a member today and receive a lot of benefits here.

chrisevan55 (not verified)

dude this just inspired a post of my own, thanks 꽁머니 사이트

123max (not verified)

sexy baccarat Anyone can play, really easy to play.

แทงบอลเว็บไหนดี (not verified)

แทงบอลเว็บไหนดี Hello there, just became aware

CHAIYO (not verified)

เว็บหวยออนไลน์ Recommend the best gambling website in them, this is really easy to play.

123abc (not verified)

วิธีเล่นสล็อตThere are many different games to choose from.

thanunya (not verified)

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

NAZA (not verified)

แฮนดิแคป online casino will bring you old favourites, new titles and old classics! There are slots wherever you go on mobile

nook (not verified)

เว็บ123 gambling website
best online

yolo (not verified)

กติกาบาคาร่า
Advantages of the lottery website

24 (not verified)

24 Quality camp casinos Technology leader, players show off their cards. Smooth app and the first 4K images

sexy baccarat (not verified)
sexy baccarat (not verified)

sexy baccarat online gambling website The best in Thailand

Abbasiseo Abbasiseo (not verified)

Loving the info on this site, you have done great job on the posts . 전국 오피사이트

uzair (not verified)

I am glad to be a visitant of this consummate web blog ! , thankyou for this rare info ! . More Info

justin (not verified)

I just couldn’t depart your site prior to suggesting that I extremely enjoyed the standard information an individual provide for your visitors? Is gonna be back frequently in order to inspect new posts superslot

seo person (not verified)

when we are looking for apartment for rents, we usually choose those with very clean rooms” superslot

Abbasiseo Abbasiseo (not verified)

An impressive share, I recently given this onto a colleague who was simply performing a little analysis for this. And then he actually bought me breakfast because I ran across it for him.. smile. So well then, i’ll reword that: Thnx for any treat! But yeah Thnkx for spending some time to discuss this, Personally i think strongly concerning this and enjoy reading much more about this topic. If you can, as you grow expertise, could you mind updating your blog site with a lot more details? It is actually extremely of great help for me. Large thumb up in this blog post! teenage psychologist near me

justin (not verified)

I like this post, enjoyed this one appreciate it for putting up. superslot

Roman khan (not verified)

I was trying to find this. Really refreshing take on the information. Thanks a lot. more info

Roman khan (not verified)

Very efficiently written article. It will be useful to anyone who employess it, as well as me. Keep up the good work – can’r wait to read more posts. visit this link

Andy (not verified)

At least the title of Limitless offers some truth in advertising. microsoft office professional plus 2019

Abbasiseo Abbasiseo (not verified)

Kippa is a free invoice generator in nigeria, invoice maker in nigeria. Also Kippa is a free online accounting software in nigeria that helps you record daily transaction, send invoice to customers in Nigeria invoice maker in nigeria

mueed Ahmed (not verified)

Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how could we communicate? دانلود موزیک شنولند

ghazanfar (not verified)

This is my first visit to your web journal! We are a group of volunteers and new activities in the same specialty. Website gave us helpful data to work. sportsbetting

mueed Ahmed (not verified)

of the asian foods that i tastes, japanese foods and thai foods are the tastiest stuff. internet providers toronto

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.[...]… voyance par téléphone

Andy (not verified)

Dale, played by Charlie Day, probably has the least horrible boss in Jennifer Aniston, playing a completely different character than people are used to seeing her in. pussy888

anus (not verified)

I discovered your blog post internet site on google and appearance some of your early posts. Keep in the really good operate. I simply additional increase your Rss to my MSN News Reader. Seeking forward to reading far more from you finding out down the road!… iflix

uzair (not verified)

you use a wonderful weblog here! do you wish to develop invite posts in my blog? mega888

Add new comment