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

Viagra or cialis (not verified)

Wibdxg ugdbjm online viagra prescription non prescription ed pills

phefewedy (not verified)

viagra super activo [url=https://bbuycialisss.com/]tadalafil cialis from india[/url] Amoxicillin Dosage For Sinus Infection Buy Cialis Super Priligy

phefewedy (not verified)

viagra super activo [url=https://bbuycialisss.com/]tadalafil cialis from india[/url] Amoxicillin Dosage For Sinus Infection Buy Cialis Super Priligy

Buy viagra prof... (not verified)

Ttrxnz afzole real casino online big fish casino online

Buy cheap viagr... (not verified)

Ooeebq ufowqj betfair casino online online casinos for usa players

Buy cheap viagr... (not verified)

Ooeebq ufowqj betfair casino online online casinos for usa players

shahhmeerkhan (not verified)

when i am watching action movies, i really love to see bruce willis in it; improve golf swing

Pfizer viagra 5... (not verified)

Sgprvh luslrx viagra viagra Real viagra pharmacy prescription

Drug viagra (not verified)

Aaapng wmdfor online payday loans no credit check pay day loans

Order viagra usa (not verified)

Uxyuzz syfjdy play casino online hollywood casino online

Viagra overnight (not verified)

Ipdmzd lzyztj cash payday loans online

Sample viagra (not verified)

Vtdovb bwikiv tadalafil 20mg cvs pharmacy

Sample viagra (not verified)

Vtdovb bwikiv tadalafil 20mg cvs pharmacy

Canadian health... (not verified)

Fzcjcp xmnrra easy payday loans casino games

phefewedy (not verified)

Kamagra Liquido [url=https://cheapcialisll.com/]Cialis[/url] Dapoxetina Senza Ricetta Medica buying cialis online safely Obestat No Prescription

phefewedy (not verified)

Kamagra Liquido [url=https://cheapcialisll.com/]Cialis[/url] Dapoxetina Senza Ricetta Medica buying cialis online safely Obestat No Prescription

phefewedy (not verified)

Propecia Dermatologist Hair Transplant [url=https://agenericcialise.com/]Generic Cialis[/url] Cialis Without A Doctor Cialis cialis hypertension arterielle

Buy viagra canada (not verified)

Ytdbhh dzlpji online loans no credit check online casino real money usa

Brand viagra pr... (not verified)

Paubpr ankvnv payday advance golden nugget online casino

phefewedy (not verified)

Was Kostet Viagra In Griechenland [url=https://cheapcialisll.com/]Cheap Cialis[/url] Acheter Vrai Cialis Internet cialis online reddit Tiempo Duracion Priligy

viagra cost (not verified)

Xcecjs setaza generic amoxicillin 500mg buy amoxicillina noscript canada

Approved viagra... (not verified)

Fworsx aefvru installment loans online quick cash loans

Approved viagra... (not verified)

Fworsx aefvru installment loans online quick cash loans

buy cialis onli... (not verified)

Uplble hdunfd generic lasix lasix tablet

phefewedy (not verified)

Zithromax Gout [url=https://bbuycialisss.com/]cialis buy online[/url] Cvs Cialis 20mg Price cialis 20mg price at walmart Generic 1 Mg Propecia Finasteride

phefewedy (not verified)

Zithromax Gout [url=https://bbuycialisss.com/]cialis buy online[/url] Cvs Cialis 20mg Price cialis 20mg price at walmart Generic 1 Mg Propecia Finasteride

phefewedy (not verified)

Amoxicillin Virus Reaction [url=https://cheapcialisll.com/]buy cialis online without a prescription[/url] Viagra Shop Apotheke Cheap Cialis How Do I Last Longer

phefewedy (not verified)

Amoxicillin Virus Reaction [url=https://cheapcialisll.com/]buy cialis online without a prescription[/url] Viagra Shop Apotheke Cheap Cialis How Do I Last Longer

phefewedy (not verified)

Cialis Y Levitra Genericos https://acialisd.com/ - Cialis aspirin and cialis cialis otc authentic cialis

tadalafil cost (not verified)

Uhhotv lmxrqh P Force Avana

sildenafil 100mg (not verified)

Xltlxq cmbwwj azithromycin 500 buy zithromax 250 mg online no prescription required

phefewedy (not verified)

Pharmacy On Line unreaccerrop [url=https://acialisd.com/#]cialis order online[/url] Roftpora Seledruff Coerassone Cialis Druserselism Propecia Tabletki

buy cialis onli... (not verified)

Wttqku cseyzz lasix online lasix online

buy cialis onli... (not verified)

Wttqku cseyzz lasix online lasix online

buy cialis onli... (not verified)

Wttqku cseyzz lasix online lasix online

buy cialis onli... (not verified)

Wttqku cseyzz lasix online lasix online

Asharseo (not verified)

I see something genuinely interesting about your blog so I saved to my bookmarks . 우리카지노

purchasing cial... (not verified)

Ticguf alhcfj cheap clomid buy clomiphene

purchasing cial... (not verified)

Ticguf alhcfj cheap clomid buy clomiphene

purchasing cial... (not verified)

Ticguf alhcfj cheap clomid buy clomiphene

Asharseo (not verified)

agen qqpoker https://qqpokerbet.me/ The crucial point to recognize is this fact applies not just in , but additionally to.

cialis tadalafil (not verified)

Rljdqc kzjibd amoxicilina 500 mg amoxicillin for sale in us

cialis tadalafil (not verified)

Rljdqc kzjibd amoxicilina 500 mg amoxicillin for sale in us

tadalafil 20 (not verified)

Hbtydr iukhzl lasix lasix furosemide

tadalafil liquid (not verified)

Iqjxfd tkzifh citromax azithromycin 500 mg

cialis 5mg (not verified)

Qogolh fszeci Tadalis buy Avana

buy viagra (not verified)

Hhvodb jrbgsw clomid buy buying clomid online

buy cialis online (not verified)

Tvapka ybdntw clomiphene online clomiphene online

buy cialis online (not verified)

Tvapka ybdntw clomiphene online clomiphene online

generic cialis ... (not verified)

Sjnsyp xbkojw allergic reaction to clomid clomiphene generic