Programmatically Create Nodes in Drupal 10

Creating nodes programmatically is a powerful technique in Drupal development, allowing you to automate content creation, import data from external sources, and build complex workflows. This tutorial will guide you through the process of creating a node in Drupal 10.

Prerequisites:

  • Basic understanding of PHP and Drupal 10 concepts.
  • Familiarity with the Drupal Entity API.
Building Blocks: Entities and Nodes

In Drupal, content is stored and managed using entities. Nodes are a specific type of entity representing individual pieces of content, such as articles, pages, or products. Each node has its own set of fields, defining its content and structure.

Creating a Node Programmatically
use Drupal\node\Entity\Node;
// Define the node type.
$node_type = 'article';
// Create a new node object.
$node = Node::create([
 'type' => $node_type,
 // Node field values.
 'title' => 'My Programmatically Created Node',
 'body' => [
   'value' => 'This is the body of my programmatically created node.',
   'format' => 'full_html',
 ],
]);
// Set additional fields (optional).
// Accessing fields by machine name.
$node->field_tags->setValue(['drupal', 'programming']);
// Save the node.
$node->save();
// Check for success.
if ($node->id()) {
 echo "Node created: " . $node->id();
} else {
 echo "Node creation failed.";
}

Explanation:

  1. Define the node type: We begin by specifying the node type we want to create. In this example, it's "article."
  2. Create a node object: We use the Node::create() method to create a new node object. We pass it an array containing the node type and any initial field values.
  3. Set field values: We set values for the title and body fields. The body field uses an array with value and format properties. You can set additional fields by referencing their machine names and using appropriate set methods.
  4. Save the node: We call the save() method to save the node object to the database.
  5. Check for success: Finally, we check if the node ID exists to confirm successful creation.


Adding the code:

There are several ways to add the code to your Drupal 10 site:

a) Custom module:

  • Create a custom module and place the code in a hook implementation. This is the recommended approach for production environments.

b) Theme template file:

  • If your code only involves simple content creation, you can place it within a theme template file.
  • This approach is not recommended for complex functionality or production environments.
Resources and further learning
Share on social media

Comment

Permalink

Quality articles or reviews is the key to attract the users to go to see the site, that's what this web site is providing.

Add new comment