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

Anonymous (not verified)

A website that does not play boredom because of a lot of games that it cannot be played properly. เกมป๊อกเด้ง

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

เว็บพนันออนไลน์ The most popular quality online gambling site at the moment

NAZA (not verified)

NAZA have any gambling game.easy to play and can play on your mobile phone.

sa casino (not verified)

คาสิโน is famous for most people because can play when you free time. can play or home, office or drive you can play all day all night.

zoom (not verified)

zoom

is the website slot casino that have all the betting in it to answer all the needed for the gambler. Betting in Soccer 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.

บอลไหล (not verified)

Recommend the best gambling website in them, this is really easy to play บอลไหล

arm168 (not verified)

A collection of casino games Complete online formเกมป๊อกเด้ง

mincc (not verified)

123 Today's football price looks like an expert

arm168 (not verified)

casino website that have all the betting in it to answer all the needed for the gamblerคาสิโนออนไลน์

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

เว็บเดิมพันออนไลน์
The best online gambling sites right now Online gambling sites with comprehensive gambling options เว็บเดิมพันออนไลน์

เว็บบาคาร่า (not verified)

เว็บบาคาร่า here are many promotions with the benefit of participating in bets

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

The number 1 popular online football betting website that has all the bets on football betting completely สูตรเซียน

heng168 (not verified)

นาซ่า Casino site with all sorts of bets.

NAZA (not verified)

แฮนดิแคป A gambling website that is different from the others

arm168 (not verified)

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

mincc (not verified)

pg 123
We have a complete range of online casino legends.
____

sa casino (not verified)

sa casino buy lily viagra
viagra buy occupation

igoal (not verified)

Igoal is famous for most people because can play when you free time. can play or home, office or drive you can play all day all night.

uzair (not verified)

This could be the proper weblog for everyone who is really wants to find out about this topic. You know a great deal of its practically not easy to argue to you (not too I just would want…HaHa). You actually put a whole new spin over a topic thats been revealed for decades. Excellent stuff, just wonderful! 토토사이트 추천

ReestVed (not verified)

free cialis pills [url=https://krocialis.com/ ]cost cialis[/url] manufacturer coupon for cialis

seo (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! 먹튀검증

Anonymous (not verified)

I discovered your site website on bing and check some of your early posts. Always maintain inside the great operate. I recently additional encourage RSS feed to my MSN News Reader. Looking for forward to reading more within you at a later time!… free firestick movie apps

sexy baccarat (not verified)

sexy baccarat
The most popular gambling game where you can make a lot of money, come play Sexy Baccarat with us now. sexy baccarat

Anonymous (not verified)

I have been exploring for a bit for any high-quality articles or blog posts on this kind of area . Exploring in Yahoo I at last stumbled upon this site. Reading this info So i’m happy to convey that I’ve a very good uncanny feeling I discovered just what I needed. I most certainly will make sure to don’t forget this site and give it a glance regularly. redi driver

Roman khan (not verified)

very nice post, i certainly love this website, keep on it iso agent program

weackAni (not verified)

rx canadian pharmacy [url=https://pharmacyken.com/ ]navarro pharmacy store locator[/url] mexican online mail order pharmacy

seo (not verified)

Great blog here! Also your site loads up fast! What host are you using? Can I get your affiliate link to your host? I wish my website loaded up as fast as yours lol mediterranean food around me

weackDev (not verified)

online classes for pharmacy tech [url=https://cjepharmacy.com/ ]best online pharmacy cialis[/url] pharmacy technician online

anus (not verified)

Music started playing anytime I opened this web site, so annoying! custom chenille patches

uzair (not verified)

HANABET adalah situs slot online terpercaya yang menyediakan platform judi online terbaik kami memberikan odds termurah untuk Taruhan bola situs slot online terpercaya

Liam1 (not verified)

This is actually impressive…Truly I don’t assume alluring ladies managing intended for web design manager is this neat. What i’m saying is actually, We get up to the and it also beats the highlights with reports! resource for writers

Anonymous (not verified)

I likewise believe thus, perfectly pent post! . รับติดตั้งกล้องวงจรปิด

amapsAsd (not verified)

cialis blaack [url=https://cialisjla.com/ ]cialis online/canada[/url] free shipping cialis usa

ReestVed (not verified)

dangers of cialis [url=https://krocialis.com/ ]cialis order[/url] time for cialis to work

weackDev (not verified)

rx online pharmacy [url=https://cjepharmacy.com/ ]canadian online pharmacy surrey bc[/url] www canadian pharmacy com

Laim (not verified)

buy pure cbd https://cfah.org/best-cbd-oil/ When I originally commented I clicked the -Notify me when new surveys are added- checkbox and from now on each time a comment is added I get four emails sticking with the same comment. Is there however you may get rid of me from that service? Thanks!

Reestloh (not verified)

dangers of cialis [url=https://rcialisgl.com/ ]goodrx.com cialis[/url] cialis works

ReestVed (not verified)

cialis online overnight shipping [url=https://krocialis.com/ ]cost of cialis[/url] fed ex overnight delivery cialis

Reestloh (not verified)

discounts on cialis [url=https://rcialisgl.com/ ]viagra vs cialis vs levitra reviews[/url] is cialis available over the counter in usa

weackGtv (not verified)

online discount pharmacy [url=https://pharmacyhrn.com/ ]walmart pharmacy online login[/url] online pharmacy tech

weackDev (not verified)

canada online drugs [url=https://cjepharmacy.com/ ]phentermine from canada pharmacy[/url] circle rx pharmacy

uzair (not verified)

Excellent blog here! Also your site loads up very fast! What host are you using? Can I get your affiliate link to your host? I wish my site loaded up as fast as yours lol car history check

uzair (not verified)

I discovered your blog internet site on bing and appearance several of your early posts. Preserve up the very good operate. I just now additional the RSS feed to my MSN News Reader. Seeking toward reading far more on your part down the road!… 5G999

anus (not verified)

As I website owner I conceive the content material here is rattling excellent , thanks for your efforts. Bunny

Mueed Ahmed (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 click here

anus (not verified)

Good – I should certainly pronounce, impressed with your web site. I had no trouble navigating through all tabs as well as related info ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your customer to communicate. Nice task. mega888

Roman khan (not verified)

infant clothing should be as comfy as possible because infants can really nag if they have bad clothing.. 스포츠토토

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 best business for cash discount program

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

แฮนดิแคป See Our Large Selection of Slots.

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

เว็บพนันออนไลน์88
Easy to play on your phone without downloading. Moreover, there are more than 3,000 slot games that you can choose to spin the slots in minutes by minute. Don't miss out on world-class slots games Come and prove yourself today

Add new comment