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

minv (not verified)

สล็อตออนไลน์
Football betting, the most stable slot game with a best friend referral system.

NAZA (not verified)

NAZA These picks are from guys who follow soccer (or football) closely.

NAZA (not verified)

NAZA
casino of thailand

ss (not verified)

bewin Recommend the best gambling website in them, this is really easy to play.

เกมบิงโก (not verified)

เกมบิงโก
เกมบิงโก The bingo game is really fun to play and can be distributed quickly

naza (not verified)

ราคาบอลแฮนดิแคป "Gather the hottest promotions That appeals to all investors
Accepting investors of many rates"

thanunya (not verified)

สล็อตออนไลน์ The best online casino website in Thailand

แฮนดิแคป (not verified)

แฮนดิแคปAll forms of online football betting can be found at our most popular betting sites.

NAZA28 (not verified)

เว็บพนันออนไลน์ Betting on online casino is the best answer for the gambler.

seo (not verified)

Thank you that is very helpful for me, as a new site has been inundated with comments that seem OK at first glance but then get repeated with a slight change of wording. I have something concrete to go on now and will delete quite a lot of them. sa casino

Mueed Ahmed (not verified)

I am glad for commenting to make you be aware of of the remarkable experience my cousin’s princess developed reading the blog. She realized a wide variety of details, including what it is like to possess a very effective teaching nature to make other individuals completely fully understand certain grueling topics. You truly surpassed our expected results. Many thanks for supplying the insightful, safe, edifying and as well as easy thoughts on that topic to Lizeth. uv sterilizer box

allbet (not verified)

allbet Casino for access to more than 1000 slot games

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

แทงบอลสเต็ป Recommend how to view football prices

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

แทงบอลสเต็ป played by Charlie Day, probably

สล็อตออนไลน์ (not verified)

สล็อตออนไลน์ The best online casino website in Thailand very good

zoom (not verified)

zoom Stable, members can withdraw as much as they want, unlimited, direct transfer, fast transfer

Naza1 (not verified)

เว็บพนันออนไลน์ Casino, Football, Lottery, Slots

fu (not verified)

fu
Good luck belongs to you throughout your investment

ss (not verified)

แฮนดิแคป Online casinos It is an online casino with a system to play through electronic tools.

III7X (not verified)

NAZA Football betting, many casino games and the best, the most modern operating system Deposit - withdraw automatically 1 minute, bill cuts fast, automatic update web, not closed, update, disturbing customers.

ตารางบิงโก (not verified)

ตารางบิงโก The best online gambling sites With every bet To meet all needs of the gambler with a complete range.

NAZA (not verified)

นาซ่า Easy to play, real pay, no cheating, only need this website 100%

เกม55 (not verified)

เกม55 We have a complete range of online casino legends.
Including more games for you to enjoy.

5678 (not verified)

เว็บคาสิโนออนไลน์ An online casino site that offers all forms of gambling for gamblers to experience a complete range of fun.

bunny bunny (not verified)

The most comprehensive online gambling game in Thailand Whether it is football betting, baccarat, slots, fish shooting games, various original gambling games are gathered here. Convenience for you all day.เว็บคาสิโน

igoal88 (not verified)

igoal88 We are the service provider Online casinos With every bet A complete answer to the gambler.

นาซ่า (not verified)

นาซ่า The best casino sites in Thailand and make good money

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

เว็บพนันออนไลน์ The number one gambling website offers the highest returns at the moment.

NAZA (not verified)

NAZA Casino Baccarat, online gambling website gambling service, online casino, many selections, Baccarat, Dragon Tiger, slots, fish shooting, deposit 1 sec, withdraw 15 sec, fastest

yolo (not verified)

naza
Many good promotions that look for both old and new customers.

yolo (not verified)

นาซ่า
Fast service and a consultant available 24 hours a day.

naza55 naza (not verified)

The best online football betting website and has a form of football betting that can meet the needs of the gambler in its entirety. เว็บคาสิโน

minc (not verified)

สล็อตออนไลน์
To help decide to place bets as well As for games like blackjack cards

naza (not verified)

คาสิโนออนไลน์ have every online betting you want to play, make a deposit-withdrawal no minimum 24 hours a day,

ตารางบิงโก (not verified)

ตารางบิงโก
ตารางบิงโก Bingo. Small investment. Get a lot of money. Play for fun and not get bored. Bingo.

zoom (not verified)

zoom World-class gambling website Fast deposits and withdrawals by a professional team 24 hours a day

thanunya (not verified)

เว็บคาสิโนออนไลน์ Fast service and a consultant available 24 hours a day.

seo person (not verified)

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

ยอดเทิร์นโอเวอร์ (not verified)

ยอดเทิร์นโอเวอร์However, with games from some game providers it's easier that with others.

igoal88 (not verified)

igoal88 There are many Sian formulas. and if you are a new customer Which formula should be used and which formula to use can be used well with what kind of games

Anonymous (not verified)

นาซ่า Football betting, many casino games and the best, the most modern operating system Deposit - withdraw automatically 1 minute, bill cuts fast, automatic update web, not closed, update, disturbing customers.

fuu88 (not verified)

spam blockers are always necessary because there are so many spam these days
fuu88

123abc (not verified)

allbet We are happy to give advice to both new and old customers. There is a quality team to serve you 24 hours a day with a fast and automatic deposit and withdrawal system.

บิงโก (not verified)

บิงโก Is the number 1 most popular online gambling website.

บิงโก (not verified)

บิงโก
Bingo game, easy to play, get real money, free credit all year round.

88 (not verified)

88 Live broadcast, take off via stream, beautiful girls deal cards, pretty, wear bikinis, increase the enjoyment of playing.

Ztevengoona (not verified)

speach buy stromectol for dogs
jemmott buy generic stromectol
order ivermectin 6mg
- buy stromectol online usa
[url=http://ivermectin-forhumans.com/#]buy ivermectin 3 mg online
[/url] mlekiemi stromectol ivermectin buy

seo (not verified)

I agree with your thought. Thank you for your sharing. Colorado Mountains

ss (not verified)

♥ ♥ igoal88♥ ♥ I discovered your site web site on bing and check many of your early posts. Maintain up the really good operate. I just additional your Feed to my MSN News Reader. Looking for forward to reading a lot more from you finding out later on!…

NAZA28 (not verified)

เว็บนาซ่า Betting on online casino is the best answer for the gambler.

Add new comment