Creating a node programmatically in Drupal 8/9

This is actually quite easy but it should be done in the correct way.

You can ignore all this and go and look at the official docs here: https://www.drupal.org/docs/drupal-apis/entity-api/working-with-the-entity-api

And that will get you started, but the tricky bit is then setting the fields. You can set the values easily:

$node_storage = \Drupal::entityTypeManager()->getStorage('node');

// Create a new unsaved node.
$node = $node_storage->create([
  'type'        => 'page',
  'title'       => 'Test page',
  'field_boolean' => [
    'value' => 0
  ],
  'moderation_state' => [
     'value' => 'published'
  ],
]);

// Save it.
$node->save();

// Get the node ID (only available after save).
$nid = $node->id();

But it’s not always easy to figure out what the values should be. For instance, if you’re referencing an entity then you need:

...
  'field_related_page' => [
    [
      'target_id' => 123
    ],
  ],
...

Remember that creating a field to only have one value doesn’t change how it’s stored. So this means that you’ll need to create a single element array containing the array that has the value for the field in it.

The easiest way to figure this out is to use Drush.

First of all create a new node in the admin backend that you can use as an example and then use Drush to get a PHP command line with Drupal loaded:

$ drush php:cli
 Psy Shell v0.10.6 (PHP 7.3.23 — cli) by Justin Hileman        

Then add a use statement to get to the Node class and load your example node:

>>> use \Drupal\node\Entity\Node;
>>> $n = Node::load(456);

Now you can get the fields in their array format to see what it is you need to do use to set a field value:

>>> $n->get('moderation_state')[0]->toArray();
=> [
     "value" => "published",
   ]         

As I mentioned above, a field value is actually an array of values of the field. So the [0] above gets the first value for the moderation state field.

0 Shares:
You May Also Like