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

Roman khan (not verified)

I really pleased to find this internet site on bing, just what I was searching for : D likewise saved to my bookmarks . Metal Hose

Abbasiseo Abbasiseo (not verified)

Utterly pent subject material , Really enjoyed reading through . CHECK ME OUT BY CLICKING MY NAME!!! Dentist Ellicott city

seo (not verified)

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

Abbasiseo Abbasiseo (not verified)

This post post made me think. I will write something about this on my blog. x Dentist 21043

uzair (not verified)

J’apprécie cette photo mais j’en ai auparavant vu de semblable de meilleures qualifications; 954 area code

ZavierKes (not verified)

cialis vs viagra cost read.cgi?board=
cialis recommended dose
buy cialis at walmart
- cialis usa
[url=https://walmartcialispharm.com]walmart cialis
[/url] purchase cialis online without a prescription

Roman khan (not verified)

The comments here were just as instructive as your post street style t shirt

Anonymous (not verified)

Wonderful beat ! I would like to apprentice whilst you amend your web site, how can i subscribe for a blog website? The account helped me a applicable deal. I had been tiny bit acquainted of this your broadcast provided shiny transparent idea. office cleaning services Perth

justin (not verified)

I like this post, enjoyed this one appreciate it for putting up. commercial cleaning Perth

uzair (not verified)

With the exception of Willis, the cast is made up of actors who have no business waving guns around. private jet
With the exception of Willis, the cast is made up of actors who have no business waving guns around. private jet

mueed Ahmed (not verified)

you possess a wonderful blog here! if you’d like to have invite posts in my small weblog? thc vape juice for sale Illinois

mueed Ahmed (not verified)

In my opinion, pick up study along with consult beneficial. medical transportation

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

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

momo (not verified)

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

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

เว็บพนันออนไลน์88
Live broadcast, take off via stream, beautiful girls deal cards, pretty, wear bikinis, increase the enjoyment of playing.

minv (not verified)

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

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

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

123maxx (not verified)

แฮนดิแคป The easiest way to check football prices.

naza55 naza (not verified)

NAZA.Aw, this became an exceptionally nice post. In thought I have to place in writing like this additionally

yolo (not verified)

แทงบอล
Good luck belongs to you throughout your investment.

88 (not verified)

88 Apply for membership and receive special privileges today.

123maxx (not verified)

แฮนดิแคป You don't have to look anywhere else, here, play games and earn real money.

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

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

Abbasiseo Abbasiseo (not verified)

Thanks for another informative blog. Where else could I get that type of info written in such an ideal way? I have a project that I’m just now working on, and I have been on the look out for such information. buy steroid online

uzair (not verified)

well, outsourcing can actually save any company several million dollars because of cheap labor., 188bet

seo (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 hotmail.com

ghazanfar (not verified)

I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it.. red rock entertainment reviews

uzair (not verified)

well, outsourcing can actually save any company several million dollars because of cheap labor., Buy Play Store downloads

mueed Ahmed (not verified)

When do you think this Real Estate market will go back in a positive direction? Or is it still too early to tell? We are seeing a lot of housing foreclosures in Oviedo Florida. What about you? Would love to get your feedback on this. airplane detailing

uzair (not verified)

This web page does not show up appropriately on my blackberry – you may want to try and repair that buy

uzair (not verified)

I absolutely adore your site! You aggressive me as able-bodied as all the others actuality and your broiled PS is absolutely great! o poder do chá de sumiço

Thank you for t... (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? สมัคร บาคาร่า ออนไลน์

uzair (not verified)

well, outsourcing can actually save any company several million dollars because of cheap labor., corpse husband reveal

Roman khan (not verified)

This is something I actually have to try and do a lot of analysis into, thanks for the post microsoft minecraft account

seo (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 microsoft office 2019 professional plus

seo person (not verified)

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

uzair (not verified)

I don’t make it a habit to make comments on many articles, but this one deserves attention. I agree with the data you have written so eloquently here. Thank you. finches for sale

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 moviesflix

chrisevan55 (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 summer dresses

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.[...]… warzone bunker locations

ghazanfar (not verified)

i never know the use of adobe shadow until i saw this post. thank you for this! this is very helpful. outlook.live.com

seo (not verified)

Hey there, or perhaps might be away from issue rather regardless, i surfing surrounding your internet-site also seems essentially truly professional. I’m also creating a new-found blogging site because trying to cope to create it bode well, each i’ve addition few things since i mess it up. In which way painful was first the site to develop your site? May perhaps one as i am without the suffer from do it right, to fit cherished ones modify documents without having to wrecking the application training? Calgary real estate listings

Andy (not verified)

noutati interesante si utile postate pe blogul dumneavoastra. dar ca si o paranteza , ce parere aveti de cazarea in regim hotelier ?. Domain name

uzair (not verified)

Trackback… […]below you’ll find the link to some sites that we think you should visit[…]… double glazing unit

Anonymous (not verified)

The primary task of a pharmacy tech is to prepare medicines for patients as per the instructions of the physicians. Other tasks of pharmacy technicians include assisting pharmacists, administrative and clerical work, as well as interacting with patients and physicians. To be able to acquire all the knowledge and skills needed for this type of career, online pharmacy technician courses can be a great choice. Focalin XR
The primary task of a pharmacy tech is to prepare medicines for patients as per the instructions of the physicians. Other tasks of pharmacy technicians include assisting pharmacists, administrative and clerical work, as well as interacting with patients and physicians. To be able to acquire all the knowledge and skills needed for this type of career, online pharmacy technician courses can be a great choice. Focalin XR

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

แฮนดิแคปThese picks are from guys who follow soccer (or football) closely.

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

แฮนดิแคป Handicap football betting to make money

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

เว็บพนันออนไลน์88
The best game providers are guaranteed to give you the best odds. to make you earn real money

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

แฮนดิแคป The best online football betting websites.

minv (not verified)

123

To choose a gambling website to play various gambling games

Add new comment