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)

ค่ายเกมสล็อต Lots of games, including many online slots betting games

bunny bunny (not verified)

casino website that have all the betting in it to answer all the needed for the gambler.นาซ่า

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

เว็บคาสิโนออนไลน์ Big websites can pay real money gambling.

naza55 naza (not verified)

ปั่นแปะA complete online gambling site in terms of a particular casino game.

NAZA28 (not verified)

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

เว็บนาซ่า (not verified)

[url=https://naza7x.com//]เว็บนาซ่า[/url] Register for free online baccarat. No need to play Baccarat Poipet, just enter the website and get real money at home. Baccarat online, Baccarat formula is very popular to make money.

bina pink (not verified)

เว็บนาซ่า Register for free online baccarat. No need to play Baccarat Poipet, just enter the website and get real money at home. Baccarat online, Baccarat formula is very popular to make money

naza (not verified)

naza The best online casino sites in Thailand and make good money.

24 (not verified)

24 Online casino sites With every bet A complete answer to the gambler.

สูตรบาคาร่า (not verified)

The bet is the highest possible return on a bet. You can bet on any team you want. กติกาบาคาร่า

III25 (not verified)

<a href="https://naza7x.com/">NAZA</a> 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.<a href="https://naza7x.com/">NAZA</a> 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.

III25 (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 bet is the highest possible return on a bet. You can bet on any team you want. กติกาบาคาร่า

naza55 naza (not verified)

เกม 55We are the service provider Online casinos With every bet A complete answer to the gambler.

คาสิโน (not verified)

<a href=https://bewin.co/>คาสิโน</a>
casino website that have all the betting in it to answer all the needed for the gambler

ss (not verified)

หาเงินออนไลน์ 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.

igoal88 (not verified)

igoal88 tadalafil 5mg price in india

naza (not verified)

สูตรบาคาร่า If today you still decide to Football betting, you may find the answer you are having questions in mind, and it can be. With that our website is a website that provides services Best online football betting สูตรบาคาร่า If today you still decide to Football betting, you may find the answer you are having questions in mind, and it can be. With that our website is a website that provides services Best online football betting

24 24 (not verified)

24
24
I am glad that it turned out so well and I hope it will continue in the future

yaiba (not verified)

หวยหุ้น No matter what kind of IT equipment and most importantly, we can play wherever we are convenient.

bina pink (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

พนันออนไลน์ (not verified)
RtgweackDev (not verified)

buy viagra canada online viagra viagra order [url=https://viagrviagrs.com/]viagra patent[/url] ’

Abbasiseo Abbasiseo (not verified)

Possible require all types of led tourdates with some other fancy car applications. Many also provide historic packs and other requires to order take into your lending center, and for a holiday in upstate New York. ??? bolatangkas

RtgweackDev (not verified)

pharmacy viagra buy generic viagra cost of viagra [url=https://viagrviagrs.com/]viagra price[/url] ’

seo (not verified)

Although, regardless how positive you actually are in treating an actual platform, at some point there are an incident wherever you should want to do some people regular supervision; and in addition dependant on your real age and in addition wellbeing, and so the body-weight using the caravan it’s really a totally hard do physical exercise. caravan touch up paint สล็อตออนไลน์

DefweackGtv (not verified)

Paxil Trimox Cilostazol [url=https://pharmpharms.com/]pharmacy online[/url] ’

BYDAYHtf (not verified)

Eskalith pharmacy rx one legitimate pharmaceutical online [url=https://storpharmon.com/]best drugstore shampoo[/url] ’

aeropVed (not verified)

cialis black buy cialis canada kГ¶pГ¤ cialis [url=https://opencialicli.com/]cialis coupons[/url] ’

Abbasiseo Abbasiseo (not verified)

dude this just inspired a post of my own, thanks house cleaning services

anus (not verified)

niggas jumpin on they favorite rapper, I will kill your favorite rapper. put him in a grave and start stumpin on your favorite rapper//. so rest in peace to yo mafuckin favorite rapper….. (I just committed suicide)… play it backwards//. . CHECK OUT MY SONG KING OF MY CITY AND SEE WHY VA WILL NEVER BE THE SAME!!. youtube smm panel

anus (not verified)

Aw, this was a very nice post. In thought I would like to put in writing like this moreover – taking time and actual effort to make an excellent article… but what can I say… I procrastinate alot and not at all appear to get something done. twitter smm panel

anus (not verified)

very good post, i surely love this excellent website, keep on it linkedin smm panel

mueed Ahmed (not verified)

Hello there, I discovered your website via Google whilst searching for a related topic, your web site came up, it seems good. I have bookmarked it in my google bookmarks. Raz Imports Christmas

Drankloh (not verified)

cialis 20 mg cialis 30 day free trial generic cialis 20mg [url=https://regcialist.com/]cialis 20mg mailorder abilene[/url] ’

seo person (not verified)

Thank you for the sensible critique. Me and my neighbor were just preparing to do a little research about this. We got a grab a book from our area library but I think I learned more clear from this post. I’m very glad to see such wonderful info being shared freely out there. buffet catering company Liverpool

mahnoor faizan (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. range finders golf

mahnoor faizan (not verified)

A great content material as well as great layout. Your website deserves all of the positive feedback it’s been getting. I will be back soon for further quality contents. see more

Kevinsaree (not verified)

gay dating largest site
gay disabled dating uk
gay dating sacramento

Abbasiseo Abbasiseo (not verified)

There is noticeably big money to comprehend this. I assume you have made certain nice points in features also. https://dailyday.com.ua/suspilstvo.html

fultyAsd (not verified)

compro viagra what is the cost of viagra buying viagra [url=https://viaedpik.com/]viagra how long does it last[/url] ’

seo (not verified)

Although, regardless how positive you actually are in treating an actual platform, at some point there are an incident wherever you should want to do some people regular supervision; and in addition dependant on your real age and in addition wellbeing, and so the body-weight using the caravan it’s really a totally hard do physical exercise. caravan touch up paint https://itholding.pl/strony-internetowe-stoczek-lukowski/

mahnoor faizan (not verified)

Superior post, keep up with this exceptional work. It's nice to know that this topic is being also covered on this web site so cheers for taking the time to discuss this! Thanks again and again! list of pages

mahnoor faizan (not verified)

Excellent website! I adore how it is easy on my eyes it is. I am questioning how I might be notified whenever a new post has been made. Looking for more new updates. Have a great day! list of pages

Drankloh (not verified)

cheapest cialis 5mg cialis cialis for free [url=https://regcialist.com/]generic medications cialis[/url] ’

brinsAni (not verified)

ambien online pharmacy best online pharmacy without prescription Tenoretic 100mg [url=https://inpharmxx.com/]drug store pharmacy technician[/url] ’

brinsAni (not verified)

canadian drug pharmacy reviews maple leaf pharmacy in canada integrity rx specialty pharmacy [url=https://inpharmxx.com/]optum rx pharmacy help desk[/url] ’

fultyAsd (not verified)

how to get viagra turmeric viagra is viagra covered by health insurance [url=https://viaedpik.com/]viagra in stores[/url] ’

allbet (not verified)

allbetll players will recognize the roulette wheel, but you might be a little put off by the table and where

bil607 (not verified)

หวยหุ้นไทยวันนี้ Lotto is another betting that a lot of people in the world play and it been in this world for many many year

Add new comment