Drupal: Creating nodes programmatically

In Drupal it is fairly easy to create nodes programmatically. But good examples for a recent version of Drupal are difficult to find.
After some searching and trying I created a few examples how to do it and how to create translations with the entity_translate module.

Creating a node

A simple snippet of code that works to add a node and a translation.

$node = new stdClass();
$node->type = 'blog';             // This type should exist
node_object_prepare($node);       // Sets some defaults.
$node->language = LANGUAGE_NONE;  // The language of the default view is undefined
$node->title = "testnode";

$node->body[LANGUAGE_NONE][0]['value'] = "Body";

node_save($node);           // Save the node

This is all that is needed to create a simple node.

Adding translations

For translations to work you first need to install and enable entity_translate,
now easiest module to support node and field level translations. Also the languages should be configured.

$node = new stdClass();
$node->type = 'blog';
node_object_prepare($node); // Sets some defaults.
$node->language = 'en';     // The language of the default view is english
$node->title = "testnode";

$node->body['en'][0]['value'] = "English body";
$node->body['en'][0]['value'] = "Nederlandse tekst";

node_save($node);           // Save the node, this is needed to get a nid

$handler = entity_translation_get_handler('node', $node); // Create a handler from entity translation

// Configuration about what to translate
$translation = array(
  'translate' => 0,
  'status' => 1,
  'language' => 'nl',          // here is the language you're translating to
  'source' => $node->language, // here is the source language
);

$handler->setTranslation($translation);
$handler->saveTranslations();

At the end of the code the node has a translation available in ‘Dutch’.
Depending on the user settings and the settings in “Detection and selection”
(admin/config/regional/language/configure) the user is presented with the dutch body or the english body.

The translate tab will show all translations that are available, every
translation can also be inspected and edited. As shown in the screenshot:

drupal_translations

Using custom fields

When you have added custom fields to a content type these can also be added in code.
A language independent field can be added with LANGUAGE_NONE and for every language the language can be given.

$node->field_id[LANGUAGE_NONE][0]['value'] = $modelnumber;

$node->field_myfield['en'][0]['value'] = $ENbody;
$node->field_myfield['nl'][0]['value'] = $NLbody;

One thought on “Drupal: Creating nodes programmatically”

Comments are closed.