How to create node programmatically in Drupal 8?

Member

by shyann , in category: PHP Frameworks , 8 months ago

How to create node programmatically in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 3 months ago

@shyann 

In Drupal 8, you can create a node programmatically by using the following steps:

  1. First, make sure to include the required namespace at the top of your PHP file:
1
2
use Drupal
odeEntityNode;


  1. Next, create a new node object:
1
2
3
4
5
$node = Node::create([
  'type' => 'article',
  'title' => 'My title',
  'body' => 'My body',
]);


  1. You can set other values for the node by adding additional key-value pairs to the array, such as the uid (user ID) or status (published or unpublished).
  2. Save the node using the save() method:
1
$node->save();


That's it! You have now created a new node programmatically in Drupal 8.