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)

Good post. I previousally to spend alot of my time water skiing and watching sports. It was quite possible the best sequence of my past and your content kind of reminded me of that period of my life. Cheers buy google traffic

تحميل العاب كمب... (not verified)

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! تحميل العاب كمبيوتر مجانا

buy web site traffic (not verified)

Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. buy web site traffic

DUBAI RECORD LABEL (not verified)

Thanks for a wonderful share. Your article has proved your hard work and experience you have got in this field. Brilliant .i love it reading. DUBAI RECORD LABEL

nad iv therapy (not verified)

I have recently started a blog, the info you provide on this site has helped me greatly. Thanks for all of your time & work. nad iv therapy

antique furnitu... (not verified)

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! antique furniture to sell

cleaning servic... (not verified)

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! cleaning services in Connecticut

Blockchain lottery (not verified)

Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. Blockchain lottery

App Store Optim... (not verified)

Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. App Store Optimization Guide

Mischief (not verified)

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! Mischief

Jonas (not verified)

Keep up the superb work, I read few content on this site and I conceive that your web blog is real interesting
and holds lots of superb information.

my page - promo (https://issuu.com)

Tara (not verified)

Very good writeup! I read your website quite regularly, and you're

constantly coming up with some good staff. I shared this post on my Twitter, and my followers loved it!

Good luck for the future.

Have a look at my web blog :: Ivan Voronkov

Remarkable (not verified)

This blog website is pretty cool! How was it made ! Remarkable

my hero academi... (not verified)

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! my hero academia manga

gift guides (not verified)

Really a great addition. I have read this marvelous post. Thanks for sharing information about it. I really like that. Thanks so lot for your convene. gift guides

voyance en direct (not verified)

I have seen some great stuff here. Worth bookmarking for revisiting. I surprise how much effort you put to create such a great informative website. Your work is truly appreciated around the clock and the globe. voyance en direct

steampunk decor (not verified)

Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. steampunk decor

UP Police Jobs (not verified)

Really a great addition. I have read this marvelous post. Thanks for sharing information about it. I really like that. Thanks so lot for your convene. UP Police Jobs

website designi... (not verified)

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! website designing in meerut

secret stash (not verified)

It is truly a well-researched content and excellent wording. I got so engaged in this material that I couldn’t wait reading. I am impressed with your work and skill. Thanks. https://www.secretstashing.com/

buy ig followers (not verified)

I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work. buy ig followers

https://www.gcc... (not verified)

I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work. https://www.gccwebhosting.com/

Sgx nifty live chart (not verified)

Thank you very much for writing such an interesting article on this topic. This has really made me think and I hope to read more. Sgx nifty live chart

Arizona First T... (not verified)

Nice blog and absolutely outstanding. You can do something much better but i still say this perfect.Keep trying for the best. Arizona First Time Home Buyer Grants

Roman (not verified)

Terrific article! That is the type of info that are meant to be shared around the internet.

Disgrace on Google for now not positioning this post upper!
Come on over and visit my web site . Thanks =)

Feel free to visit my homepage; coupon (https://www.instapaper.com/p/7187834)

affiliate marketing (not verified)

I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work. affiliate marketing

frontend backen... (not verified)

Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign. frontend backend integration

Domino QQ (not verified)

I know this is one of the most meaningful information for me. And I'm animated reading your article. But should remark on some general things, the website style is perfect; the articles are great. Thanks for the ton of tangible and attainable help. Domino QQ

Judson (not verified)

Very good writeup. I read your blog site quite often, and you're continuously coming up with some good staff.

I shared this blog post on my Tumblr, and my followers loved it.

Good luck for the future.

Look into my site - Gordey Pokrovsky

advanced regene... (not verified)

Thank you for sharing a bunch of this quality contents, I have bookmarked your blog. Please also explore advice from my site. I will be back for more quality contents. advanced regenerative orthopedics

location voitur... (not verified)

Thank you for very usefull information.. location voiture agadir

Wilfred (not verified)

You have made some good points there. I looked on the net to

find out more about the issue and found most people will go

along with your views on this web site.

My weblog :: Agen Poker

gambar bokep (not verified)

gambar bokep

web hosting provider (not verified)

Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign. web hosting provider

atlanta headshots (not verified)

Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign. atlanta headshots

Cna training cl... (not verified)

Best American Healthcare University offers CNA certification training classes in riverside ca. We also have CNA programs in Ontario. Our profound Nursing Assistant training course is one of the premier in the Inland Empire. We have weekend and weekday schedules. We offer CNA training for Ontario, CA residents, Rancho Cucamonga, Fontana, Upland, Pomona, Corona, Moreno Valley, and the whole of Inland Empire (Riverside and San Bernardino counties) Cna training classes corona ca

salesforce sms app (not verified)

Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign. salesforce sms app

voyance amour t... (not verified)

I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work. voyance amour telephone

αποφραξεις (not verified)

Η εταιρεία Apofraxeis, δραστηριοποιείται στο χώρο της συντήρησης, απόφραξης, καθαρισμού αποχετευτικών αγωγών και μεταφορών λυμάτων από το 1960. Διαθέτοντας πολυετή εμπειρία και τα πιο σύγχρονα αποφρακτικά μηχανήματα διασφαλίζουμε την ΕΓΓΥΗΣΗ των εργασιών μας, με ΧΑΜΗΛΟ ΚΟΣΤΟΣ και ταχύτατους χρόνους εξυπηρέτησης. αποφραξεις

robinsontranspo... (not verified)

I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work. robinsontransport.co.uk

robinsontranspo... (not verified)

I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work. robinsontransport.co.uk

CB01 (not verified)

Site about movie and tv shows in italian and free CB01

manchester unit... (not verified)

I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work. manchester united adidas

his secret obsession (not verified)

Pretty good post. I have just stumbled upon your blog and enjoyed reading your blog posts very much. I am looking for new posts to get more precious info. Big thanks for the useful info. his secret obsession

http://www.wind... (not verified)

Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign. http://www.windewa8.net

نزيل ببجي للكمبيوتر (not verified)

I exactly got what you mean, thanks for posting. And, I am too much happy to find this website on the world of Google. تنزيل ببجي للكمبيوتر

Robinjack (not verified)

I’m new to your blog and i really appreciate the nice posts and great layout.”`-.; reviews for phen375

numero voyance ... (not verified)

I really impressed after read this because of some quality work and informative thoughts . I just wanna say thanks for the writer and wish you all the best for coming!. numero voyance gratuit

numero voyance ... (not verified)

I really impressed after read this because of some quality work and informative thoughts . I just wanna say thanks for the writer and wish you all the best for coming!. numero voyance gratuit

Add new comment