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

Ken (not verified)

The function file_unmanaged_copy is deprecated in Drupal 8.7. How can you do this in Drupal 8.7?

MichaelLef (not verified)

how much does viagra cost generic viagra
how long does viagra last female viagra
how long does viagra last
how much does viagra cost
http://www.lzmfjj.com/Go.asp?URL=https://canpharmb3.com
http://www.seishinka-file.info/rank.php?mode=link&id=3469&url=https://canpharmb3.com/
http://link.amf.org.au/c/3/?T=TmpVMk56WTFOVGc6WWpFek1URTJMVFl6T1RNNVl6aGtMVFUwTjJVdE5HTXhZUzFpWXpZd0xURTFNVGc1T0Rkak1tVTNNUTpjR0poZVd4cGMzTkFjMnBqYUdWc2MyVmhMbU5oZEdodmJHbGpMbVZrZFM1aGRROlkyOXVkR0ZqZEMxallqaGlaR0l4TlRZMU16UmxNekV4T1dVNFlqQXdOVEExTmpnek1tTmtNQzAwWTJFMFpqQTJPRE0wTldRME5HWmhPVGxqT0RZeVpHWmxZVE13TkRBM1lR&K=gy5vkfyNvICwNb4dwN8neg&m=t&uId=1&durl=https://canpharmb3.com
http://www.dogsitting.fr/scripts/redirect.asp?url=https://canpharmb3.com/

Aimee (not verified)

Please let me know if you're looking for a article author for your blog.

You have some really great posts and I feel I would be a good asset.

If you ever want to take some of the load off, I'd really like to write

some material for your blog in exchange for a link back to mine.

Please shoot me an email if interested. Thank you!

Here is my page ... แจกเครดิตสล็อต

MichaelLef (not verified)

how much does viagra cost generic viagra
how long does viagra last female viagra
how long does viagra last
how much does viagra cost
http://www.lzmfjj.com/Go.asp?URL=https://canpharmb3.com
http://www.seishinka-file.info/rank.php?mode=link&id=3469&url=https://canpharmb3.com/
http://link.amf.org.au/c/3/?T=TmpVMk56WTFOVGc6WWpFek1URTJMVFl6T1RNNVl6aGtMVFUwTjJVdE5HTXhZUzFpWXpZd0xURTFNVGc1T0Rkak1tVTNNUTpjR0poZVd4cGMzTkFjMnBqYUdWc2MyVmhMbU5oZEdodmJHbGpMbVZrZFM1aGRROlkyOXVkR0ZqZEMxallqaGlaR0l4TlRZMU16UmxNekV4T1dVNFlqQXdOVEExTmpnek1tTmtNQzAwWTJFMFpqQTJPRE0wTldRME5HWmhPVGxqT0RZeVpHWmxZVE13TkRBM1lR&K=gy5vkfyNvICwNb4dwN8neg&m=t&uId=1&durl=https://canpharmb3.com
http://www.dogsitting.fr/scripts/redirect.asp?url=https://canpharmb3.com/

Felipe (not verified)

I always used to study piece of writing in news papers but now as I am a user of net thus from now I am

using net for articles, thanks to web.

Stop by my page :: แจกเครดิตฟรี

Stephaine (not verified)

What's up, its good piece of writing regarding media print, we all know media is a enormous source of facts.

Also visit my webpage; slotxo

Katrin (not verified)

Hello it's me, I am also visiting this web site regularly, this web page is in fact nice and the

viewers are actually sharing fastidious thoughts.

Feel free to visit my web site: king189

Francesco (not verified)

I read this post fully regarding the difference of latest and

earlier technologies, it's awesome article.

Look into my webpage :: สล็อตออนไลน์

Cathy (not verified)

Can you tell us more about this? I'd love to find out some additional information.

Have a look at my homepage ทัวร์เกาหลี

Nelsemove (not verified)

indian pharmacy what are the side effects of cialis
viagra vs cialis natural viagra
coffee with cialis
24 hour pharmacy
http://ntubh.cc/space-uid-211080.html
http://bbs.mcrst.com/home.php?mod=space&uid=393904
http://www.gzbjjl.com/home.php?mod=space&uid=2934
http://www.ppfyq.com/home.php?mod=space&uid=198267
http://www.haribaby.com/home.php?mod=space&uid=1042

Charlesfog (not verified)
Arleen (not verified)

Hello, every time i used to check web site posts here early in the dawn, for the reason that i

like to find out more and more.

Also visit my web site; แจกเครดิตฟรี

PeterOvace (not verified)

canadien cialis cialis lowest price
how to get cialis samples daily use of cialis
side effects for cialis
generic cialis no doctor's prescription
http://www.bsalud.es/iop/ezs.phtml?url=http://cialisxtl.com
http://oohboobsmovies.com/cgi-bin/atx/out.cgi?id=59&trade=http://cialisxtl.com
http://www.partyghost.be/go.php?url=http://cialisxtl.com
http://www.myxxxanalsex.com/df/out.cgi?ses=il3fjcw0la&id=6&url=http://cialisxtl.com

PeterOvace (not verified)

canadien cialis cialis lowest price
how to get cialis samples daily use of cialis
side effects for cialis
generic cialis no doctor's prescription
http://www.bsalud.es/iop/ezs.phtml?url=http://cialisxtl.com
http://oohboobsmovies.com/cgi-bin/atx/out.cgi?id=59&trade=http://cialisxtl.com
http://www.partyghost.be/go.php?url=http://cialisxtl.com
http://www.myxxxanalsex.com/df/out.cgi?ses=il3fjcw0la&id=6&url=http://cialisxtl.com

Izetta (not verified)

Thanks for sharing your thoughts on ทัวร์ญี่ปุ่น.

Regards

PeterOvace (not verified)

cialis maximum dosage hard erections cialis
generic cialis coming out does cialis lower blood pressure
how long does 20mg cialis keep in system
cialis 20 mg best price
http://www.a-fuu.com/out_ad.php?url=http://cialisxtl.com
http://www.snrproject.com/Resource/Extermal_Link?url=http://www.cialisxtl.com/
http://sutd.ru/links.php?go=http://cialisxtl.com
http://www.regardinghealth.com/click/default2.asp?bmkEPM=14052&t=cus&i=83855&go=http://cialisxtl.com

Add new comment