Drupal - Programmatically create nodes

The following code will help you to save an image in a new node.

use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;

// 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(),
    'alt' => 'Hello world',
    'title' => 'Goodbye world'
  ],
]);
$node->save();

For more information, see http://realityloop.com/blog/2015/10/08/programmatically-attach-files-node-drupal-8.


In drupal 8 entities are objects and as such, to create an entity is to create an instance of the entity's type class. If you know the class of the entity then you can either use the new keyword or the create function.

I.E. $foo = new Foo(); or $foo = Foo::create();

If you don't know the class of entity (only the machine name) then you can use the request the Storage class like so: \Drupal::entityTypeManager()->getStorage($entity_type_id)->create();

To populate the fields of an entity you can either use the $entity->set($key, $value) method on the entity object or pass a key=>value array to the entity constructor. As such:

$foo = new Foo([
  'name'=>'bar',
  'baz'=> TRUE,
  'multi_value' => [
    'first',
    'second',
    'third',
  ]
]);

To save an entity you only have to call the $entity->save() method on the entity object.

Since files in drupal 8 are also entities you need to either pass the id of the file entity, or the actual file entity, as the value.

$file_1 = File::load(1);
$foo->set('bar_files', [
  $file_1,
  2
]);

Here is a code for your specific scenario:

$node_entity_type = \Drupal::entityTypeManager()->getDefinition('node');
// The [file_save_upload][1] function returns an array of all the files that were saved.
$poster_images = file_save_upload($upload_name, $validators, $destination);
$node = new Node([
  $node_entity_type->getKey('bundle') => 'movie',
  $node_entity_type->getKey('label') => 'Foo',
  'field_release_date' => '1/1/2015',
  'field_poster_image' => $poster_images,
]);
$node->save();

I think that object oriented way is more convenient, isn't it?

use Drupal\node\Entity\Node;

$my_article = Node::create(['type' => 'article']);
$my_article->set('title', 'My article');
$my_article->set('field_text', 'My text');
$my_article->set('field_image', FID);
$my_article->set('field_user', UID);
$my_article->enforceIsNew();
$my_article->save();

Tags:

Nodes

8