Skip to content

How to add an image field programmatically Drupal 8/9/10

Drupal1 min read

To add an image field programatically in drupal 9 first we will need to add the file in the files table and then pass the file ID to the field, have a look at the below code on how to do it

use Drupal\file\Entity\File;
$file = File::create([
'uri' => $url,

Add the file id to the image field

$node = \Drupal\node\Entity\Node::create([
'type' => 'page',
'title' => 'Foobar',
'field_my_image' => [
'target_id' => $file->id(),
'alt' => 'Alternative name',

Hope this helps !!!

© 2023 by Thakshashila. Alll rights reserved.
Built using Gatsby
Theme Credits : LekoArts