How to create node programmatically in Drupal 8?

Member

by shyann , in category: PHP Frameworks , 2 years ago

How to create node programmatically in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by filiberto , 2 years 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.

by darrion.kuhn , a year ago

@shyann 

To create a node programmatically in Drupal 8, you can use the following steps:

  1. First, create a new instance of the node entity using the entity manager:
1
2
3
4
use Drupal
odeEntityNode;

$node = Node::create();


  1. Set the node type:
1
$node->setType('article');


Replace 'article' with the desired node type machine name.

  1. Set the node title and body:
1
2
3
4
5
$node->setTitle('My Node Title');
$node->set('body', [
  'value' => 'My Node Body',
  'format' => 'basic_html', // Define the input format of the body value
]);


  1. Set any other desired fields for the node. For example, to set a taxonomy term reference field:
1
$node->set('field_tags', [1, 2, 3]); // Replace 'field_tags' with your field name and [1, 2, 3] with the term IDs you want to assign


Replace 'field_tags' with your field name and [1, 2, 3] with the desired term IDs.

  1. Save the node:
1
$node->save();


That's it! Now you have created a node programmatically in Drupal 8.