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

igoal (not verified)

Igoal
IgoalWe are the service provider Online casinos With every bet A complete answer to the gambler

123maxx (not verified)

แฮนดิแคป Recommend the best gambling website in them, this is really easy to play.

123abc (not verified)

In the past, if a gambler was to play a slot game, he would have to play at a foreign casino. ค่ายเกม

บอลสเต็ป (not verified)

บอลสเต็ป Easy to apply for NAZA membership just a few steps

ไฮโล (not verified)

ไฮโลThai Hi-Lo website, Local Hi-Lo has been very popular. And today we bring it to customers to bet easily

minb (not verified)

123
To choose a gambling website to play various gambling games

CHOKDE (not verified)

หวยออนไลน์ You don't have to look anywhere else, here, play games and earn real money.

minb (not verified)

pg 123"We have a complete range of online casino legends.
We have top casinos from all over the world gathered here in one place."

naza (not verified)

naza have classic gambling game.

yolo (not verified)

บอลสเต็ป
Are you looking for money

uzair (not verified)

A person necessarily lend a hand to make severely posts I’d state. This is the very first time I frequented your web page and to this point? I surprised with the analysis you made to make this particular submit extraordinary. Magnificent process! proentpreneurs

justin (not verified)

you’ve gotten an ideal weblog right here! would you like to make some invite posts on my weblog? Palm Beach Gardens Swimming Pool Contractor

uzair (not verified)

A person necessarily lend a hand to make severely posts I’d state. This is the very first time I frequented your web page and to this point? I surprised with the analysis you made to make this particular submit extraordinary. Magnificent process! outsourcing

seo (not verified)

A person necessarily lend a hand to make severely posts I’d state. This is the very first time I frequented your web page and to this point? I surprised with the analysis you made to make this particular submit extraordinary. Magnificent process! deneme bonusu

Azlescam (not verified)

cialis doses member list
viagra, cialis or levitra. which is best
cialis over the counter walmart
- cialis 20mg tablets who is online
[url=http://cialis-unlimited.com]walmart coupon for cialis
[/url] cialis and alcohol consumption i forgot my password

123 (not verified)

123 Lots of betting games. Sports. Casino. Slots.

123 (not verified)

Bet with the leading sports betting site at 123

igoal (not verified)

Igoal
Igoal
The best online gambling sites With every bet To meet all needs of the gambler with a complete range

TT21 (not verified)

<a href="https://igoal24.vip/">igoal </a> Online gambling service providers That answers all needs Excellent gambler 24 hours a day.

<a href="https:... (not verified)

Online gambling service providers That answers all needs Excellent gambler 24 hours a day.

<a href="https:... (not verified)

Online gambling service providers That answers all needs Excellent gambler 24 hours a day.

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

เว็บพนันออนไลน์88

New style slots games that are played online And supports playing on both Android and ios mobile phones that are comfortable to play And also a play that does not limit the area to generate money Suitable for players in this age very much. Our website is ready to provide services that meet the needs of the players the most.

NAZA28 (not verified)

NAZA New members receive a 50% bonus Live casino system is very good. Fast deposit and withdrawal Ready to serve 24 hours.

bewin (not verified)

bewin secure licensing and the outstanding app are just a few advantages that this giant in the world of casino and sports betting ...

igoal88 (not verified)

igoal88 Online casino sites that includes online gambling

mins (not verified)

123
Sports betting We have an online football betting service. Every league to choose from to win a play.

ไฮโล (not verified)

ไฮโลHi-Lo, deposit, withdraw, no minimum, fast, timely, take no more than 2-3 minutes, fast service, pay attention to customers. every detail

123เกม (not verified)

123เกม
online casinos that offer a wide variety of betting

Anonymous (not verified)

123
Guaranteed by the service for a long time.

naza (not verified)

naza is a casino online with automatic deposit and withdrawal system.our system very fast and safe.

naza (not verified)

ราคาบอลแฮนดิแคป for who want to play at the casino but do not want to travel to the real casin

seo person (not verified)

when we are looking for apartment for rents, we usually choose those with very clean rooms” click here

seo (not verified)

good day, your site is really unquie. Anways, i do appreciate your work yowhatsapp

mins (not verified)

pg 123
Understand how to play To play online slots to make money. To start, you need to understand.

Anonymous (not verified)

igoal
Online casinos Baccarat online for real money free trial play

uzair (not verified)

Making sure you know all about News became valuable to most of people. Boxing Body Bag

seo (not verified)

Whoah this blog is magnificent i really like reading your articles. Keep up the good paintings! You realize, a lot of persons are searching round for this information, you could aid them greatly. SMM panel India

seo person (not verified)

kaufen sie high heels schuhe und pumps in der schweiz online hier! stöckelschuhe

Abbasiseo Abbasiseo (not verified)

His acting here consists of a shtick(acting like a total wimp) that I have seen many times before and better. do my programming homework

Abbasiseo Abbasiseo (not verified)

Hi i would really love to subscribe and read your blog posts , pay for programming homework

anus (not verified)

When I originally commented I clicked the -Notify me when new surveys are added- checkbox and from now on every time a comment is added I purchase four emails using the same comment. Could there be by any means you are able to get rid of me from that service? Thanks! 188

mueed Ahmed (not verified)

I have read several excellent stuff here. Definitely price bookmarking for revisiting. I wonder how much attempt you set to make such a fantastic informative web site. prp treatment

alveena seo (not verified)

All I'm trying to tell you is that don't act like you're more polite than the poets and no man can give more respect than you.
f95zone

Zelonit (not verified)

verklaring stromectol for chickens
vucbwimugw ivermectin sheep drench
ivermectin 3 mg tablets
- stromectol lice
[url=http://ivermectin3mg.com/#]ivermectin scabies how fast does it work
[/url] targetid ivermectin stromectol side effects

เว็บ 123 (not verified)

เว็บ 123Our guide to the best free online casino table games in 2021.

88 (not verified)

88
Welcome everyone to the zoom88 website, online casino gambling website. The most popular of the year 2020-2021 offers members to gamble, live casino, baccarat, slots, tiger-dragon cards.

เว็บ 123 (not verified)

เว็บ 123 Our website is an online gambling

เว็บ88 (not verified)

เว็บ88 Football betting, the most stable slot game with a best friend referral system.

123 (not verified)

Online casino website The best at the moment 123

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

เว็บพนันออนไลน์ Here you will find a new type of casino that will make you enjoy all kinds of betting.

Add new comment