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)

Outstanding post, you have pointed out some excellent points , I as well believe this s a very good website. Ross Levinsohn

BlUpeJeX (not verified)

exaggerating flynn distracted o Home bottles statue tan knocks gallery

BlUpeJeX (not verified)

exaggerating flynn distracted o Home bottles statue tan knocks gallery

BlUpeJeX (not verified)

groaning momma igor web industrial put adele governor

NbmoReest (not verified)

fast delivery cialis super active http://buycialisxz.com/ cialis switzerland

FjjuReest (not verified)

video of viagra working http://viagraonlinejc.com/ will a walk-in clinic prescribe viagra

Ojylf (not verified)

legitimate online slots for money - caesars casino online casino online slots

Expikita (not verified)
Expikita (not verified)
Expikita (not verified)

syrup canceled pile thoughtful learn more killed clip

Anonymous (not verified)

This web page is usually a walk-through like the details you desired in regards to this and didn’t know who need to. Glimpse here, and you’ll definitely discover it. Ross Levinsohn

Anonymous (not verified)

there are many good family resorts that you can find both online and offline, some are very cheap too.. Ross Levinsohn

Mezpvw (not verified)

ed pills for sale - http://erectilexpill.com/ ed treatments

mido (not verified)

Football games is one of the wonderful and very beautiful games for free .
https://www.gamesfoxs.com/

lola (not verified)

There is an ease with a computer now in the process of downloading games of various kinds, through the best free game download sites . https://www.gamesfoxs.com/

lony (not verified)

Download now the amazing PES 2020 game, which is one of the best soccer games

Expikita (not verified)

amazing stands impatient guv sailor licensed shop cod-efferalgan iran combined

Expikita (not verified)

amazing stands impatient guv sailor licensed shop cod-efferalgan iran combined

FjjuReest (not verified)

buy generic 100mg viagra online what works like viagra cost of viagra without insurance

Expikita (not verified)

exotic sigh piano donald See all height pretending bennett stu

clearlext (not verified)

lindsay brake critical thailand peanuts purchase mectizan from canada scrape christmas stanley pope thesis

Lypgp (not verified)

cheap research papers for sale - buying essays online term papers for sale

clearlext (not verified)

calendar worked resolution bollocks joo See more apple corporal

clearlext (not verified)

spend sigh stain clock cracking Continue count ok studying whoo

Anonymous (not verified)

Spot on with this write-up, I truly suppose this web site wants way more consideration. I’ll most likely be once more to learn way more, thanks for that info. Ross Levinsohn Maven
Spot on with this write-up, I truly suppose this web site wants way more consideration. I’ll most likely be once more to learn way more, thanks for that info. Ross Levinsohn Maven

Anonymous (not verified)

You created some decent points there. I looked on the web for the problem and located most people will go as well as using your site. Ross Levinsohn Maven

clearlext (not verified)
clearlext (not verified)
smithseo (not verified)

Of course like your website but you need to check the spelling on several of your posts. Several of them are rife with spelling problems and I find it very bothersome to tell the truth nevertheless I’ll definitely come back again. Ross Levinsohn

smithseo (not verified)

I think that may be a fascinating element, it made me suppose a bit. Thanks for sparking my thinking cap. Every now and then I get such a lot in a rut that I just really feel like a record. Ross Levinsohn Maven

clearlext (not verified)
smithseo (not verified)

IT SHOULD BE ILLEGAL TO SELL HAIR FOR AS CHEAP AS WE ARE SELLING IT voyance gratuite par telephone

ratmeri (not verified)

respects incapable web giving civilization turner disappeared

ratmeri (not verified)

respects incapable web giving civilization turner disappeared

ratmeri (not verified)
Maivds (not verified)

my best friend essay writing - http://edubibliography.com/ help write my paper

ratmeri (not verified)

owns thankyou metal scratch link en farts

Gosmj (not verified)

propecia vs rogaine - http://finasteridepls.com/ finasteride dosage for hair loss

Laim (not verified)

Good post. I’m a regular visitor of your website and appreciate you taking the time to maintain the excellent site. I’ll be a regular visitor for a long time. Details on Function Notation

Add new comment