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

cheap cialis ge... (not verified)

can woman take cialis

will gabapentin (not verified)

Levitra Generico 20 Mg Prezzo

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

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

propecia 1mg (not verified)

Achat Cialis Montreal

viagra pfizer o... (not verified)

Canadian Pharmacy 24 Hr

best site to bu... (not verified)

cialis 30 free trial

wikipedia viagra (not verified)

Voveran Is It Available In The Us

buy zithromax 1... (not verified)

Amoxicillin Diarrhea

viagra and low ... (not verified)

Amoxil Chats Melange

proscar order b... (not verified)

Viagra Uk Retailers

propecia over t... (not verified)

Cialic Best Price 5mg Canada

cheapest propecia uk (not verified)

Lasix Denmark

slot (not verified)

wer1866@hotmail.com

123ABC (not verified)

ค่ายเกมสล็อต Many online betting games

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

Really easy to play, 100% not cheating.

123ABC (not verified)

เกมส์ยิงปลาonline fish shooting games that is easy to play, does not require luck

baccarat (not verified)

espresso1866@hotmail.com