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

FilliepneuB (not verified)

theodore roosevelts version cialis
online canadian pharmacy cialis
cialis over the counter
- can cialis for women
[url=https://cialis1walmart.com]cialis over the counter at walmart
[/url] cialis 20mg review administrators

seo (not verified)

Music started playing anytime I opened this web site, so annoying! https://mystrucuturedsettlement.net

anus (not verified)

I like the valuable information you provide in your articles. I’ll bookmark your blog and check again here frequently. I’m quite certain I will learn plenty of new stuff right here! Good luck for the next! 바카라사이트

seo (not verified)

I am glad that it turned out so well and I hope it will continue in the future because it is so worthwhile and meaningful to the community. IncredibleMagazine

uzair (not verified)

Hello, i just planned to drop that you a line to say that we thoroughly enjoyed this particular post from yours, I have subscribed for your RSS feed and have absolutely skimmed several of your articles or blog posts before but this blog really endured out in my situation. call center

ZrestGalge (not verified)

buying cialis good sites
cialis pro review
cialis over counter walmart
- cialis commercials settings
[url=https://walmartpharm.com]cialis over counter at walmart
[/url] gallery menalto cialis

Zaynenouby (not verified)

kamagra reviews 20 mg replies
kamagra from the uk
buy ajanta india kamagra
- best price genuine kamagra
[url=https://kamagradc.com/#]kamagra jelly
[/url] kamagra from india

TozOralf (not verified)

joanne stevens, ivermectin ivermectin drug interactions
cycloneanti facilities
ivermectin cream over the counter
- podnikali newscaster
[url=https://invermectindc.com/#]ivermectin tablets for humans
[/url] durata uprima ivermectin ivermectin

seo (not verified)

I am glad that it turned out so well and I hope it will continue in the future because it is so worthwhile and meaningful to the community. 온라인바카라

seo (not verified)

I am glad that it turned out so well and I hope it will continue in the future because it is so worthwhile and meaningful to the community. 온라인 바카라

Andy (not verified)

Nice weblog here! Additionally your website loads up very fast! What host are you the usage of? Can I get your associate hyperlink on your host? I wish my site loaded up as quickly as yours lol. 바카라사이트

seo (not verified)

Thanks, I’ve recently been seeking for facts about this topic for ages and yours is the best I’ve found so far. 먹튀검증사이트

Abbasiseo Abbasiseo (not verified)

I would like to consider the ability of thanking you for that professional guidance I have often enjoyed checking out your site. I’m looking forward to the particular commencement of my college research and the entire prep would never have been complete without dropping by your site. If I may be of any assistance to others, I’d personally be glad to help as a result of what I have gained from here. รีวิวคาสิโน

Abbasiseo Abbasiseo (not verified)

I am glad that it turned out so well and I hope it will continue in the future because it is so worthwhile and meaningful to the community. รีวิวคาสิโน

uzair (not verified)

Just now you can branch out from your daily understanding. Don’t give up your morals for anything. This will lead to a sad and unfulfilling life. 토토사이트

uzair (not verified)

Man that was very entertaining and at the same time informative.’:;;. 토토사이트

Andy (not verified)

I must express my gratitude for your generosity for those who must have help with this important concern. Your very own dedication to passing the message along ended up being exceptionally functional and has specifically encouraged most people like me to arrive at their aims. This warm and friendly guidelines denotes this much to me and substantially more to my mates. Thanks a lot; from all of us. Exotic Birds for Sale

seo (not verified)

I'm not against the agree with the things you suggested. Online Poker

Andy (not verified)

Everything you need to know about News in a great way. สล็อตออนไลน์

Andy (not verified)

Aw, this became an exceptionally nice post. In thought I have to place in writing like this additionally – spending time and actual effort to make a good article… but exactly what can I say… I procrastinate alot and by no means often go carried out. สล็อตออนไลน์

Abbasiseo Abbasiseo (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. uvb t5 vs t8

Anonymous (not verified)

You should take part in a contest for one of the best blogs on the web. I will recommend this site! reptisun 10.0 t5 36

seo (not verified)

Hi there, just became aware of your blog through Google, and found that it’s really informative. I’m gonna watch out for brussels. I’ll be grateful if you continue this in future. Many people will be benefited from your writing. Cheers! 토토

seo (not verified)

Nice blog entre. I really have to say, good work. uwatchfree

LhdvReest (not verified)

overnighted cialis for men http://asciled.com/ cialis forsale

Abdgweack (not verified)

pharmacy online https://canadianeve21.com/ Brand Levitra

Lrbsweack (not verified)

levitra trial offer [url=http://uslevitraanna.com/ ]levitra samples free[/url] viagra cialis levitra canada

Andy (not verified)

You made various nice points there. I did a search on the theme and found nearly all people will go along with with your blog. 바카라사이트

Andy (not verified)

I am often to blogging and that i actually appreciate your posts. This article has truly peaks my interest. I am going to bookmark your internet site and keep checking for first time data. 바카라사이트

Andy (not verified)

Hey there! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no data backup. Do you have any methods to stop hackers? 바카라

Anonymous (not verified)

“this is very interesting. thanks for that. we need more sites like this. i commend you on your great content and excellent topic choices.” 바카라

SEO (not verified)

I am glad that it turned out so well and I hope it will continue in the future because it is so worthwhile and meaningful to the community. missing adult

RfvbReest (not verified)

cialis dapoxetine europe http://cileve.com/ cialis with dapoxetine or viagra with dapoxetine better

RfvbReest (not verified)

cialis dapoxetine europe http://cileve.com/ cialis with dapoxetine or viagra with dapoxetine better

RfvbReest (not verified)

cialis 10mg http://cileve.com/ real cialis

Bbdfmodo (not verified)

viagra without a doctor prescription canada https://gensitecil.com/ best generic viagra

LhdvReest (not verified)

buy cialis without doctor prescription [url=https://asciled.com/ ]cialis 36 hour dosage[/url] how much is cialis without insurance

Lrbsweack (not verified)

generic levitra [url=https://uslevitraanna.com/ ]free trial levitra[/url] levitra samples

Andy (not verified)

I come across your webpage from cuil and it’s high quality. Thnkx for giving this sort of an incredible article.. maltese puppies for adoption near me

LhdvReest (not verified)

cialis 20 mg [url=http://asciled.com/ ]order cialis 20 online[/url] genericcialis

ZillTow (not verified)

where can i buy cialis tadalafil in ipswich town
best price for cialis
cialis walmart
- cialis 20mg tablets who is online
[url=https://pharmacywalmart.com]cialis otc
[/url] buy cialis online total posts

ZillTow (not verified)

where can i buy cialis tadalafil in ipswich town
best price for cialis
cialis walmart
- cialis 20mg tablets who is online
[url=https://pharmacywalmart.com]cialis otc
[/url] buy cialis online total posts

Gvdbamaps (not verified)

tadalafil 7mg [url=https://boxtadafil.com/ ]tadalafil cialis[/url] tadalafil 5mg price in india

Jbsdweack (not verified)

medication costs [url=http://onlinecanda21.com/ ]cheap prescription drugs online[/url] pharmacy

Lrbsweack (not verified)

levitra cooper http://uslevitraanna.com/ levitra blood pressure

seo (not verified)

Hello there, just became aware of your blog through Google, and found that it’s really informative. I am going to watch out for brussels. I’ll be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers! https://action-rehab.com/how-to-stop-drinking-alcohol/

Jazonaloli (not verified)

buy lily viagra
viagra buy occupation
viagra for sale
- viagra online profile
[url=https://vgsnake.com/#]viagra for sale
[/url] shout box latest message viagra

ZilliepneuB (not verified)

cialis side effects with alcohol bbs.cgi?
cialis samples
cialis for men
- cialis 5 mg coupon board index
[url=https://cialisbin.com]how many milagrams should i take of cialis
[/url] www.cialis

Jbsdweack (not verified)

cialis daily [url=http://onlinecanda21.com/ ]Motrin[/url] Vasotec

seo (not verified)

I am glad that it turned out so well and I hope it will continue in the future because it is so worthwhile and meaningful to the community. 메이저사이트

Add new comment