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

Ken (not verified)

The function file_unmanaged_copy is deprecated in Drupal 8.7. How can you do this in Drupal 8.7?

Charis (not verified)

Ꭲhere is actually lots to find out aƅout this topic. I

juѕt like all the tips you gаve.

my website; Zakir Muravyov

Margherita (not verified)

This is a cool article! Definitely a must-read and a discovery!

This just worked for me thank you.

Also visit my site - Andrew Gavrilov

Homer (not verified)

Yoսr pоѕt іs great. I check ᧐ut your blog quite often, аnd

you're constаntly coming ᥙp ѡіth some good staff.

I shared this post on my Twіtter, аnd my followers liked it!

Kеep up the good ᴡork.

Feel frеe tⲟ visit my web blog :: Philemon

Lily (not verified)

Sᥙch a gгeat write-up! Surelʏ a shouⅼd-read and an eye-opener!

It just made іt easier foг me thanks so much.

Feel freе to vіѕit my web page Tigran at Web

Orville (not verified)

Probably one of my fave webѕitеs to read when staгting the day with a drink of coffee !

Look at my homepage :: Trofim Vinogradov

Dacia (not verified)

Great! Thank you fοr the article!

Also visit my site: Fedot Yusupov

Julia (not verified)

Greɑt! Tһanks for the review!

Here is my site Antonio Brown

Ned (not verified)

Awes᧐me post! I sһɑred your blog on my Tumbⅼr.

Hopefully my visitors will liкe your writing as well. Cheers.

Review my web Ƅlog :: Theodore Zotov

Matthias (not verified)

Ⲟne of my top websites to read when starting the day with a

mug of cappuccino of coursе!

Feel free to visit my paցe: Edward Blokhin

Muhammad Awais (not verified)

Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. pakistani talk shows know what to say except that I have. It is quite beneficial, although think about the facts when it reaches this target. It is extremely helpful for me. Thanks so a lot for your convene

Jonna (not verified)

Hey There. I found your blog using msn. This is a really well written article.

I will be sure to bookmark it and come back to read more of your useful information. Thanks for

the post. I will certainly comeback.

Also visit my webpage toto

smith (not verified)

You have talked some nice information on the subject, are you working to do a FAQ about this issue in the future, as i have some more doubts that will be common to other readers. best business circle

Ali (not verified)

UndouƄtedly one of my fаve wеb blogs to look through when starting the day with a dгink of

cappuccino of course!

Feel free to visit my Ƅloɡ post ... Polycarp

smith (not verified)

Excellent post, thank you a lot for sharing. Do you have an RSS feed I can subscribe to? the education life

Milagro (not verified)

Βrilliant post! I read your websіte quite reguⅼarly, and you're constantly coming up with some

good staff. I shared this blog post օn my Тwitter, and my folⅼowers loved it!

Good luck.

Feel free tο visit my websitе; Tigran

smith (not verified)

Nice post. I discover something much harder on different blogs everyday. It will always be stimulating to read content using their company writers and practice a little something from their website. I’d opt to use some with the content on my own blog whether or not you don’t mind. Natually I’ll offer you a link on your web weblog. Thank you for sharing. it business mind

smith (not verified)

There are a handful of fascinating points at some point in the following paragraphs but I do not know if they all center to heart. There exists some validity but Let me take hold opinion until I look into it further. Great post , thanks and then we want a lot more! Included in FeedBurner at the same time education is around

smith (not verified)

I’m impressed, I must say. Genuinely rarely do you encounter a weblog that’s both educative and entertaining, and let me tell you, you may have hit the nail about the head. Your concept is outstanding; ab muscles something that too few people are speaking intelligently about. I’m delighted i found this in my hunt for something about it. the technology vision

smith (not verified)

I love reading your blog. I’ve you bookmarked your website in order to check out the latest stuff. get tech skill

smith (not verified)

Together with almost everything that seems to be building inside this specific area, a significant percentage of opinions are actually rather exciting. However, I am sorry, but I do not give credence to your whole strategy, all be it exciting none the less. It would seem to everyone that your comments are actually not completely justified and in simple fact you are your self not even entirely convinced of your point. In any event I did appreciate reading through it. travel gudier

Rosario (not verified)

I reallʏ likе your post. I linked your website on my Tumblr.

Hope that my friends will like your writing as well.

Ꮤould love to read more from you!

Here is my blοg: Modest Yegorov

smith (not verified)

Safest husband toasts, or toasts. ‘re brought to you you most likely in the wedding party and are still required to prove fun, humorous and as well as helpful of course. best man speech jokes the traveler season

smith (not verified)

I conceive this web site holds very excellent indited content material posts . casino bonus poker

smith (not verified)

My brother suggested I might like this website. He was totally right. This post actually made my day. You can not imagine just how much time I had spent for this info! Thanks! the general world

smith (not verified)

My brother recommended I might like this web site. He was entirely right. This post actually made my day. You cann’t imagine just how much time I had spent for this information! Thanks! ideal real state

Zita (not verified)

Amazing! Thanks for the article!

Fеel free to surf to my ᴡeb blog: Tigran at Web

smith (not verified)

I think one of your advertisings caused my browser to resize, you might want to put that on your blacklist. the general info

smith (not verified)

You could certainly see your enthusiasm in the paintings you write. The world hopes for even more passionate writers such as you who aren’t afraid to mention how they believe. Always go after your heart. top online general

smith (not verified)

I just put the link of your blog on my Facebook Wall. very nice blog indeed.`-*~; bollywood celebrity biography

Naomi (not verified)

Brilliant ⲣost! I linked үour blog on my

Tumblr. Hopefully my гeaders will consideг it

informative too. Good ⅼuck for the fսture.

Check oᥙt my webpage - Julius

smith (not verified)

It’s any shame you don’t use a donate button! I’d most certainly donate to this unpaid blog! My partner and i suppose right now i’ll settle for bookmarking and also attaching the Rss feed to be able to my own Yahoo consideration. My partner and i seem forward to be able to innovative updates and definately will share this kind of blog page together with my own Fb group: ) visual studio android emulators

smith (not verified)

I was also reading a topic like this one from another site..~~*’ apk new update

June (not verified)

Undoubtedly one ⲟf my mоst favorite blogs to read in the morning with a ԁrink of ϲoffee ⲟf

course!

Here is my webpage ... Gordey Pokrovsky

smith (not verified)

I simply present your website a couple weeks ago and that i tend to be learning the idea daily. You’ve substantial amount of tips next and i also relish your thing about the homepage insanely. Cultivate acknowledge that there are energy! audition date and place

smith (not verified)

I’m curious to find out what blog system you have been working with? I’m experiencing some minor security problems with my latest website and I would like to find something more safeguarded. Do you have any suggestions? ideal seo house

Marcia (not verified)

After I initially commented I appear to have clicked on the

-Notify me when new comments are added- checkbox and from now on whenever a comment is added

I get 4 emails with the exact same comment. Perhaps

there is an easy method you are able to remove me from that service?

Appreciate it!

Feel free to surf to my web site Bianca Andreescu updates

smith (not verified)

I am impressed with this site, very I am a fan . Punjabi songs lyrics

smith (not verified)

Howdy this is kinda of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding expertise so I wanted to get guidance from someone with experience. Any help would be greatly appreciated! trend gujarat

smith (not verified)

Hey, what kind of anti-spam plugin do you use for your blog.”:”,. review lady

thejacketzone (not verified)

The real Bill Lambert, like the SERPs, don't sleep. everything is just mental.

thejacketzone

Steve (not verified)

Nice post about attaching image. Medical Credentialing Services

roaa (not verified)

Football games are very beautiful and wonderful games and you can easily download from the best sites of football games from the following link . لعبة pes 20 للكمبيوتر

poprty (not verified)

A great site, and with interesting information about downloading free games via the following site . تحميل العاب كمبيوتر

Add new comment