Creating a node in code

by Gisle Hannemyr

This is a brief note about creating a node in code,.

Table of contents

Introduction

The code in this tutorial presents a simple example of how to create a node in PHP code.

We are going to do it by creating a custom module with a controller to create the node. The custom module to create the node in code shall be named “Hello Node”, with the machine name “hellonode”.

You start by creating a directory with the name “hellonode” in the directory modules/custom below the webroot.

Create hellonode.info.yml

Move into the cirectory you just created, and create the file hellonode.info.yml to hold information about the custom module:

name: Hello Node
description: Custom module to demonstrate how to create a node programatically.
core_version_requirement: ^8.8 || ^9 || ^10
type: module
package: custom

This is the minimum required to have a custom module. As soon as this has been created, you should be able to navigate to Manage » Extend » List and see this custom module.

Create a controller

First, create a directory to hold the controller, the change into that directory, and finally create an empty file named "HelloNodeController.php":

$ mkdir -p src/Controller
$ cd src/Controller
$ thouch HelloNodeController.php

Use your favourite text editor to put the follwing PHP code inside "HelloNodeController.php":

<?php

namespace Drupal\hellonode\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;

/**
 * Creates a node in code.
 */
class HelloNodeController extends ControllerBase {

  /**
   * Creates a node.
   */
  public function createhello() {
    $article = [
      'title' => 'Hello, World!',
      'body' => 'This is a node created in code.',
    ];
    $newArticleNode = $this->createArticleNode($article);
    $element = [
       '#markup' => '<p>' . t('Created new article node.') . '</p>',
    ];
    return $element;
  }

  protected function createArticleNode($article) {
    $new_article = Node::create(['type' => 'article']);
    $new_article->set('title', $article['title']);
    $new_article->set('body', [
      'value' => $article['body'],
      'format' => 'basic_html',
    ]);
    $new_article->enforceIsNew();
    // Set status to unpublished.
    $new_article->status = 0;
    $new_article->save();
    return true;
  }

}

Custom fields added to a content type using the GUI will have a human label and a machine name. The machine name will start with field, usually followed by a lowercase ASCII version of the project name and field label separated by underscores. When using the wrapper, values can be assigned to the machine name. Example:

$new_article->set('field_hellonode_myfieldname', 'value');

Create a route

Finally create the file hellonode.routing.yml to make the controller accessible from the GUI.

hellonode.hello_node:
  path: '/hellonode'
  defaults:
    _controller: '\Drupal\hellonode\Controller\HelloNodeController::createhello'
    _title: 'Hello world'
  requirements:
    _permission: 'access content'

If your site's name is "example.com", visiting the following URL: "https://example.com/hellonode" will create a new node.

Final word

Alternative method, using dependency injection: DO: Dependency Injection example.


Last update: 2023-05-09 [gh].