Skip to content

Instantly share code, notes, and snippets.

@gargsuchi
Created April 12, 2017 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gargsuchi/863a556c732b6fab89c99f0bdaa4d2f1 to your computer and use it in GitHub Desktop.
Save gargsuchi/863a556c732b6fab89c99f0bdaa4d2f1 to your computer and use it in GitHub Desktop.
<?php
/**
* @file
* Contains lotus.module.
*/
use Drupal\node\Entity\Node;
/**
* Helper function to create a new node.
*/
function create_new_node(){
$node = Node::create(['type' => 'YOUR_NODE_TYPE']);
$node->set('title', 'YOUR_TITLE');
//Body can now be an array with a value and a format.
//If body field exists.
$body = [
'value' => 'YOUR_BODY_TEXT',
'format' => 'basic_html',
];
$node->set('body', $body);
$node->set('uid', YOUR_UID);
$node->status = 1;
$node->enforceIsNew();
$node->save();
drupal_set_message("Node with nid " . $node->id() . " saved!\n");
}
@mstekl
Copy link

mstekl commented Sep 25, 2019

Just a quick note: drupal_set_message() is deprecated since 8.5. Be sure to use \Drupal\Core\Messenger\MessengerInterface::addMessage() instead.

@gargsuchi
Copy link
Author

@mstekl
I agree, but you do realize this is an old gist :)

@mstekl
Copy link

mstekl commented Sep 25, 2019

I do, but since it is linked from Aquia's documentation, I thought it might be worth the note in case other people ends on this old gist too :-)

@gargsuchi
Copy link
Author

Makes sense. Did not realize that this gist is linked.

@mosesliao
Copy link

I got this error InvalidArgumentException: Field body is unknown.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment