How to programmatically create a node in Drupal 8?

chapka picture chapka · Jun 11, 2014 · Viewed 23.6k times · Source

I'm designing a new module in Drupal 8. It's a long-term project that won't be going public for a few months at least, so I'm using it as a way to figure out what's new.

In this module, I want to be able to programmatically create nodes. In Drupal 7, I would do this by creating the object, then calling "node_submit" and "node_save".

These functions no longer exist in Drupal 8. Instead, according to the documentation, "Modules and scripts may programmatically submit nodes using the usual form API pattern." I'm at a loss. What does this mean? I've used Form API to create forms in Drupal 7, but I don't get what the docs are saying here.

What I'm looking to do is programmatically create at least one and possibly multiple new nodes, based on information not taken directly from a user-presented form. I need to be able to:

1) Specify the content type

2) Specify the URL path

3) Set any other necessary variables that would previously have been handled by the now-obsolete node_object_prepare()

4) Commit the new node object

I would prefer to be able to do this in an independent, highly abstracted function not tied to a specific block or form.

So what am I missing?

Answer

Rookie Rod picture Rookie Rod · Aug 5, 2015

use Drupal\node\Entity\Node;

$node = Node::create(array(
    'type' => 'your_content_type',
    'title' => 'your title',
    'langcode' => 'en',
    'uid' => '1',
    'status' => 1,
    'field_fields' => array(),
));

$node->save();