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

uzair (not verified)

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post… 메이저사이트

Fbsfweack (not verified)

Abilify https://uspharmus.com/ canadian drugs

Fbsfweack (not verified)

Abilify https://uspharmus.com/ canadian drugs

RfvbReest (not verified)

fast delivery cialis super active https://cileve.com/ online cialis florida delivery

Abdgweack (not verified)

canadian online pharmacies prescription drugs [url=https://canadianeve21.com/ ]walmart online pharmacy[/url] Ventolin inhalator

Bbdfmodo (not verified)

how to make viagra at home https://gensitecil.com/ what happens when women take viagra

seo (not verified)

This blog really is good. How was it made ? Virtual assistant services

Fbsfweack (not verified)

Aldactone http://uspharmus.com/ canadian online pharmacies

uzair (not verified)

Thanks a lot for your interesting article. I have been searching for such message for a very long time. Not all your content is completely clear to me, even though it is definitely interesting and worth reading. friday night funkin

uzair (not verified)

You should take part in a contest for one of the best blogs on the web. I will recommend this site! fnf unblocked games

Fbsfweack (not verified)

generic viagra online [url=http://uspharmus.com/ ]online prescription drugs[/url] Zerit

Jbsdweack (not verified)

medication costs http://onlinecanda21.com/ Allopurinol

Gvdbamaps (not verified)

tadalafil generic date [url=https://boxtadafil.com/ ]tadalafil 20mg how long before sex[/url] how long does tadalafil last

Bbdfmodo (not verified)

otc viagra usa http://gensitecil.com/ canada viagra

LhdvReest (not verified)

viagra vs cialis vs levitra reviews https://asciled.com/ cheapest cialis canada

Andy (not verified)

An impressive share, I given this onto a colleague who was simply carrying out a small analysis for this. And that he in reality bought me breakfast due to the fact I found it for him.. smile. So allow me to reword that: Thnx for your treat! But yeah Thnkx for spending plenty of time to talk about this, I’m strongly regarding it and enjoy reading much more about this topic. If you can, as you grow expertise, could you mind updating your site to comprehend details? It can be extremely ideal for me. Big thumb up just for this blog post! 파워볼

sg (not verified)

This can be in addition a great article i genuinely liked looking at. It's not at all every day i contain the probability to view a thing. cheap youtube views
This can be in addition a great article i genuinely liked looking at. It's not at all every day i contain the probability to view a thing. cheap youtube views
cheap youtube views

Andy (not verified)

dress up is always a great and exciting one, or strip poker. Perhaps get some dice from a game board and decide if you land on certain numbers what those actions are. Spice it up is always a great thing!! 파워볼

so (not verified)

I’m curious to find out what blog system you’re utilizing? I’m having some small security problems with my latest website and I would like to find something more risk-free. Do you have any recommendations? 파워볼데이터

RfvbReest (not verified)

cialis without precription [url=https://cileve.com/ ]cialis online doctor[/url] generic cialis

Lrbsweack (not verified)

levitra 20 [url=https://uslevitraanna.com/ ]viagra vs levitra vs cialis[/url] cheap levitra 20mg

Abdgweack (not verified)

on line pharmacy https://canadianeve21.com/ Motilium

Abdgweack (not verified)

on line pharmacy https://canadianeve21.com/ Motilium

RfvbReest (not verified)

cialis 20mg П„О№ОјО· https://cileve.com/ cialis lilly 20mg

RfvbReest (not verified)

cialis 20mg П„О№ОјО· https://cileve.com/ cialis lilly 20mg

LhdvReest (not verified)

cialis generic canada pharmacy https://asciled.com/ cialis 20mg price

Laim (not verified)

The when I just read a blog, I really hope it doesnt disappoint me approximately this place. Get real, Yes, it was my choice to read, but I just thought youd have some thing intriguing to express. All I hear can be a couple of whining about something that you could fix if you werent too busy interested in attention. marginal revenue formula

Laim (not verified)

[...]usually posts some very interesting stuff like this. If you’re new to this site[...]… friedlieb ferdinand runge

Laim (not verified)

You made some decent points there. I looked on-line for the issue and located most people should go along with along with your internet site. ebitda formula

Laim (not verified)

The the next time Someone said a weblog, Hopefully that this doesnt disappoint me about this place. Get real, Yes, it was my replacement for read, but When i thought youd have something intriguing to say. All I hear is actually a couple of whining about something that you could fix if you werent too busy in search of attention. marginal revenue formula

Laim (not verified)

Have you ever considered about adding a little bit more than just your articles? I mean, what you say is fundamental and all. But think of if you added some great visuals or videos to give your posts more, “pop”! Your content is excellent but with pics and clips, this blog could undeniably be one of the best in its niche. Very good blog! friedlieb ferdinand runge

Laim (not verified)

I rattling happy to find this site on bing, just what I was searching for : D likewise saved to favorites . ebitda formula

Laim (not verified)

After study many of the blogs in your internet site now, and i genuinely as if your technique of blogging. I bookmarked it to my bookmark site list and you will be checking back soon. Pls check out my internet site also and inform me what you think. friedlieb ferdinand runge

Laim (not verified)

Hey very nice website!! Man .. Beautiful .. Amazing .. I’ll bookmark your blog and take the feeds also…I’m happy to find a lot of useful information here in the post, we need work out more strategies in this regard, thanks for sharing. . . . . . ebitda formula

Laim (not verified)

After study many of the content for your web site now, i truly as if your way of blogging. I bookmarked it to my bookmark site list and are checking back soon. Pls have a look at my site also and figure out how you feel. marginal revenue formula

Laim (not verified)

There are a few interesting points soon enough in this article but I don’t determine if every one of them center to heart. There is certainly some validity but I am going to take hold opinion until I investigate it further. Excellent post , thanks so we want far more! Added to FeedBurner too friedlieb ferdinand runge

Laim (not verified)

I am only in order that willing to ought to see this. It’s the version of handbook that is loaned and never the very animal falsehoods might be on extra content. Recognize the value of your main showing such largest file. ebitda formula

Laim (not verified)

I just couldn’t leave your site prior to suggesting that I extremely loved the usual info a person provide in your guests? Is gonna be again often to investigate cross-check new posts. Surface Area of a Cone

Laim (not verified)

I just couldn’t leave your site prior to suggesting that I extremely loved the usual info a person provide in your guests? Is gonna be again often to investigate cross-check new posts. Surface Area of a Cone

Laim (not verified)

Hey mate, thanks for writing but this page doesn’t format correctly in Netscape it is showing only half the page. Negative Exponents

Laim (not verified)

I have to obtain the likelihood of saying thanks to the individual for ones experienced pointers I have got regularly treasured going over the sites. We’re waiting for often the beginning pertaining to my own education background work and also the uncut practice could not continues to be finalize whilst not having traveling to your online site. N’ t simply may possibly from a profit to folks, Detailed enjoy it to aid of what Regarding seen from this point. Installing Music Paradise App in Android

Laim (not verified)

What your declaring is absolutely true. I know that everyone need to say the similar factor, but I just feel that you set it in a way that everybody can comprehend. I also love the images you place in right here. They suit so well with what youre attempting to say. Im sure youll attain so quite a few folks with what youve received to say. Double Declining Balance

Laim (not verified)

I am glad to be a visitant of this double dyed weblog, regards for this rare info! business quotes

Laim (not verified)

I am just commenting to make you know of the fabulous encounter my wife’s daughter gained using your webblog. She picked up plenty of pieces, with the inclusion of what it’s like to have an amazing coaching style to make men and women completely know precisely several complex subject matter. You truly exceeded our own desires. Thanks for delivering those beneficial, healthy, educational and even fun tips about this topic to Sandra. during gastrulation in frogs, a rod of mesoderm under the dorsal surface forms the _____.

Laim (not verified)

There is evidently a lot to identify about this. I feel you made some nice points in features also. rainbow bridge dog

Laim (not verified)

Aw, this is a really nice post. In notion I would like to invest writing like this moreover – taking time and actual effort to create a top notch article… but what can I say… I procrastinate alot through no indicates apparently go done. larry david net worth

robinjack (not verified)

This is a great write-up. Thank you for spending some time to describe all of this out for folks. It really is a great help! brazilian blowout cost

Laim (not verified)

That is the suitable weblog for anybody who desires to search out out about this topic. You understand a lot its almost onerous to argue with you (not that I really would want…HaHa). You undoubtedly put a brand new spin on a topic thats been written about for years. Nice stuff, simply nice! billy mckeague

Laim (not verified)

Nice post. I understand some thing much harder on diverse blogs everyday. Most commonly it is stimulating to study content using their company writers and rehearse a little something from their store. I’d would prefer to apply certain with all the content in this little blog regardless of whether you don’t mind. Natually I’ll provide link on your web blog. Many thanks sharing. psychoactive salvias

Laim (not verified)

Youre so cool! I dont suppose Ive read anything similar to this prior to. So nice to locate somebody by original thoughts on this subject. realy we appreciate you beginning this up. this excellent website are some things that is required on the internet, an individual with a little originality. beneficial job for bringing new things to the net! iceland on world map

Add new comment