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.
Table of Contents
Create a node of a specific content type in Drupal 8/9
Create a node entity generated by DrupalnodeEntityNode 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 DrupalnodeEntityNode;
//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 DrupaluserEntityUser 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 DrupaluserEntityUser;
$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 DrupaltaxonomyEntityTerm 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 DrupaltaxonomyEntityTerm;
$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.