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

heng168 (not verified)

สูตรรูเล็ต Betting is the most return rate in betting. You can bet in any team that you want to bet. Also, it real live time betting so you cannot miss this bet at all, I gaurantee you.

naza19 (not verified)

นาซ่า Play in every type of casino as real casinos have. Like a small casino in the form Online casinos

minx (not verified)

เว็บคาสิโน
We have a complete range of online casino legends.

Zuhapaymn (not verified)

apromiskuity buy stromectol
istenmeyen stromectol buy
buy ivermectin for humans
- ivermectin praziquantel
[url=http://ivermectin4sale.com/#]ivermectin tablets
[/url] pornofilmer how to inject ivermectin in a dog

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

กติกาบาคาร่า Nice blog entre. I really have to say, good work

แทงบอลออนไลน์ (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.

weackHtf (not verified)

cialis for sale [url=https://cialishav.com/ ]cheap cialis pills online[/url] cialis muscle pain

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

เว็บคาสิโน
เว็บคาสิโน The best online gambling sites With every bet To meet all needs of the gambler with a complete range

weackAni (not verified)

Zestril [url=https://pharmacyken.com/ ]israel online pharmacy[/url] best online international pharmacies

weackHtf (not verified)

cialis sell [url=https://cialishav.com/ ]cialis los angeles[/url] 20 mg cialis not working

Abbasiseo Abbasiseo (not verified)

I’d must talk with you here. Which is not something It’s my job to do! I love reading a post that can get people to think. Also, many thanks for permitting me to comment! sugaring paste

uzair khatri (not verified)

Interesting blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple tweeks would really make my blog jump out. Please let me know where you got your design. With thanks visit this site

seo (not verified)

Cheap Kasper Suits… [...]listed below are a couple of urls to internet websites we connect to for the fact we feel they really are really worth browsing[...]… letterman jacket patches

seo (not verified)

Its such as you read my mind! You appear to understand a lot about this, like you wrote the e-book in it or something. I believe that you simply could do with a few % to force the message house a bit, however other than that, this is wonderful blog. A great read. I'll certainly be back. click here

Zoblehes (not verified)

prijatelny generic ivermectin
impacts stromectol for osteoporosis
by stromectol online usa
- ivermectin pill
[url=http://stromectoloverthecounter.com/#]what is stromectol used for
[/url] uitzicht medendazole (vermox), ivermectin (stromectol), or albendazole (albenza). reviews

Mueed Ahmed (not verified)

There is evidently a lot to know about this. I consider you made certain nice points in features also. sexy

justin (not verified)

I discovered your blog web site on the internet and appearance many of your early posts. Always maintain in the really good operate. I simply additional the Feed to my MSN News Reader. Looking for toward reading a lot more of your stuff at a later time!… Personal Injury Attorney

Abbasiseo Abbasiseo (not verified)

There is noticeably big money to understand about this. I suppose you have made certain nice points in functions also. ตรวจสลากกินแบ่งรัฐบาล

Laim (not verified)

I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much. cardboard box with window lid

justin (not verified)

Music started playing anytime I opened this web site, so annoying! swimming pool builder in wellington

Zertstupe (not verified)

dusunceler stromectol is used for?
tjokro stromectol prix en pharmacie
ivermectin for coronavirus
- ivermectin dosage for chickens
[url=http://ivermectin4humans.com/#]ivermectin for dogs
[/url] sympathiser oral ivermectin

ดูราคาบอล (not verified)

ดูราคาบอล, would love to hear your guys early picks for the first weekend of matches!

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

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

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

เว็บพนันออนไลน์88New 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. Our website is ready to provide services that meet the needs of the players the most.

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

แฮนดิแคป techniques and formulas In handicap football betting for everyone

naza55 naza (not verified)

NAZA.If you are looking for a real money gambling website Here we have all the bets you need. Play on your smartphone anytime, anywhere.

123maxx (not verified)

123 I really like your writing style, wonderful information.

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

แฮนดิแคปBetting is the most return rate in betting. You can bet in any team that you want to bet. Also, it real live time betting so you cannot miss this bet at all, I gaurantee you.

bewin (not verified)

bewin
bewin The number 1 online gambling web service provider with the most traffic.

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

เว็บคาสิโน would love to hear your guys early picks for the first

คาสิโน (not verified)

คาสิโนPopular online casinos.

123maxx (not verified)

แฮนดิแคป 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.

zoom (not verified)

zoom
In addition to the money transfer system Through every bank application, we are still a website for automatic deposits and withdrawals with no minimum. that doesn't have to chat to contact the staff to queue up Making financial transactions by the Auto system will start with a minimum withdrawal of 100 baht.

mins (not verified)

123 Today's football price looks like an expert

Scoesaido (not verified)

discharging ivermectin for cats fleas
superficiels how long does ivermectin last
stromectol price
- buy stromectol tablets
[url=http://stromectol-otc.com/#]stromectol
[/url] panier stromectol online brighter tomorrow

NAZA (not verified)

naza have classic gambling game.

สูตรเซียน (not verified)

สูตรเซียน are highly secured sites. And there are many online casinos to choose from.

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

สูตรรูเล็ต Hello there, just became aware of your blog through Google, and found that it’s really informative.

naza55 naza (not verified)

ปั่นแปะStraight to the point and well written! Why can’t everyone else be like this?

igoal (not verified)

igoalTop gambling sites Best football betting website Best online casino Supervised by experts And a professional team for quick deposit-withdrawal.

mins (not verified)

เว็บคาสิโน
Sports betting We have an online football betting service. Every league to choose from to win a play.

Anonymous (not verified)

แฮนดิแคป "the popular online casino offers daily
cashback to the players. "

naza19 (not verified)

กติกาบาคาร่า Online casinos There are always new promotions for customers

uzair (not verified)

Unquestionably believe that which you said. Your favorite justification seemed to be on the web the simplest thing to be aware of. I say to you, I certainly get irked while people consider worries that they just don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks Strategies for trading in Currencies

Laim (not verified)

Thanks for another wonderful post. Where else could anybody get that type of info in such an ideal way of writing? custom match boxes wholesale

mueed (not verified)

I wonder if this is all possible, see for yourself. brighter future

Mueed Ahmed (not verified)

Hello my family member! I wish to say that this post is amazing, great written and come with approximately all vital infos. I would like to see extra posts like this . Maven CEO Mr. Levinsohn

justin (not verified)

Hi there terrific blog! Does running a blog like this take a massive amount work? I’ve absolutely no expertise in coding but I had been hoping to start my own blog soon. Anyway, should you have any suggestions or techniques for new blog owners please share. I understand this is off subject but I just needed to ask. Many thanks! Sbobetauto

แทงบอลออนไลน์ (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)

เว็บคาสิโน
เว็บคาสิโน The best online gambling sites With every bet To meet all needs of the gambler with a complete range

Add new comment