Saving and Updating Nodes with the $node->language Property

Well, you can certainly learn something new about Drupal everyday. I spent a good bit of time trying to figure out why I couldn't perform a simple field value update to a few nodes in an application. So, node_save() was running without error, and nothing I attempted to update in the node object or related fields would save.

After some investigation, I noticed these problem nodes were originally created without a defined language property ($node->language). I just happened to see this by looking at the "node" table and sorting by the language field in the Drupal database. While Drupal allowed the application create the original nodes without setting the language property, it led to issues when performing an update to the node. My conclusion is that the language property should always be set.

Below I have some examples which illustrate saving a new node and updating an existing node with $node->language set properly.

Create a node object and save it (Drupal 7)

<?php
$node = new stdClass();
$node->type = 'content_type';
$node->title = 'Node Title';

// Set the language.
$node->language = LANGUAGE_NONE;

// Custom field.
$node->field_custom[$node->$language][0]['value'] = 'Custom field data';

// Prepare and save the node.
node_object_prepare($node);
$node = node_submit($node);
$node->revision = TRUE;
node_save($node);

Update a node object and save it (Drupal 7)

<?php
// Load a node with nid = 1000.
$node_nid = 1000;
$node = node_load($node_nid);

// Change the title of the node.
$node->title = 'New title';

// Update the value of a field with the language property of the node object.
$node->field_custom[$node->$language][0]['value'] = 'New custom field data';

// Set the revions property and save the updated node.
$node->revision = TRUE;
node_save($node);

Note that LANGUAGE_NONE is a constant that can be used when no particular language is specified (See: Drupal API documentation). If you need to set a language, you can with the locale module.

Blog Category: