How to Create Entities (node, user, term) programmatically in Drupal 8/9

lakshmi , Credit to  volkotech-solutions Jan 07

Create an entity programmatically by using the method Drupal::entityManager() in drupal 8. The Drupal::entityManager has been removed in Drupal 9.x and should be replaced with Drupal::entityTypeManager. To create entities, use the create() method of the entity manager service.

Create a node of a specific content type in Drupal 8/9

Create a node entity generated by Drupal\node\Entity\Node and create node object by using Node::create() function. The alternate method to create a node entity by using create() method of the Drupal::entityTypeManager service.

Method 1:

<?php   
use Drupal\node\Entity\Node;
//The article is a machine name of a bundle of a content type.
    $node = Node::create(array(
        'type' => 'article',
        'title' => 'your title',
        'langcode' => 'en',
        'uid' => '1',
        'status' => 1,
        'field_fields' => array(),
    ));
    $node->save();

Method 2:

<?php   
 
//The article is a machine name of a bundle of a content type.
$node = \Drupal::entityTypeManager()->getStorage('node')->create([
     'type' => 'article',
     'title' => 'your title',
     'langcode' => 'en',
     'uid' => '1',
     'status' => 1,
   ]);
   $node->save();

Create a user with a specific role in Drupal 8/9

Create a user entity generated by Drupal\user\Entity\User and create a user object by using the User::create() function. The alternate method to create a user entity by using create() method of the Drupal::entityTypeManager service.

Method 1:

<?php
use Drupal\user\Entity\User;
 
$user = User::create([
     'name' => 'username',
     'pass' => 'userpassword',
     'mail' => 'user@gmail.com',
     'status' => 1,
     'roles' => array('manager','administrator'),
    ]);
$user->save();

Method 2:

<?php   
$user = \Drupal::entityTypeManager()->getStorage('user')->create([
     'name'     => 'username',
     'pass' => 'userpassword',
     'mail'      => 'user@gmail.com',
     'status' => 1,
      'roles' => array('manager','administrator'),
   ]);
   $user->save();

Create a term of a specific vocabulary in Drupal 8/9

Create a term generated by Drupal\taxonomy\Entity\Term and create a term object by using the Term::create() function. The alternate method to create a term of a specific vocabulary by using create() method of the Drupal::entityTypeManager service.

Method 1:

<?php
use \Drupal\taxonomy\Entity\Term;
$term = Term::create([
     'name' => 'term_name',
     'vid' => 'vocabulary_machine_name',
   ]);
   $term->save();

Method 2:

<?php
 $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->create([
     'name' => 'term_name',
     'vid' => 'vocabulary_machine_name',
   ]);
   $node->save();

Conclusion:

That's all! You have successfully created entities (node, user, term) by using the create() method of the entity manager service.

Comments