Skip to content

Instantly share code, notes, and snippets.

@johnny-aroza
Last active October 14, 2019 09:49
Show Gist options
  • Select an option

  • Save johnny-aroza/3defd2e566bf20a021090792a2f9071a to your computer and use it in GitHub Desktop.

Select an option

Save johnny-aroza/3defd2e566bf20a021090792a2f9071a to your computer and use it in GitHub Desktop.
Custom code to create new mode for article and basic page

Drupal 7 method The following code snippet can be used wherever there is a requirement to add a new node, being sure to replace <title> and with their actual values.

global $user;
  $node = new stdClass();
  $node->title = "<title>";
  $node->type = "<node>";
  node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
  $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
  $node->uid = $user->uid;
  $node->status = 1; //(1 or 0): published or not
  $node->promote = 0; //(1 or 0): promoted to front page
  $node = node_submit($node); // Prepare node for saving
  node_save($node);
  drupal_set_message( "Node with nid " . $node->nid . " saved!\n");

Drupal 8 method The following code snippet can be used wherever there is a requirement to add a new node, being sure to replace <node_type>, <title>, <body_text>, and with their actual values.

use Drupal\node\Entity\Node;
$node = Node::create(['type' => '<node_type>']);
$node->set('title', '<title>');

//Body can now be an array with a value and a format.
//If body field exists.
$body = [
'value' => '<body_text>',
'format' => 'basic_html',
];
$node->set('body', $body);
$node->set('uid', <uid>);
$node->status = 1;
$node->enforceIsNew();
$node->save();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment