Creating nodes programmatically in Drupal (including cck and location fields)

Creating a new node in drupal is trivial, but when the node includes custom cck fields, then a few things can trip you up. To save time and energy, here’s a quick guide and some tips to make your drupal life easier.

Creating a basic node:

global $user; //get current logged in user
$new_node = new stdClass();
$new_node->type = 'YOUR_NODE_TYPE_HERE';
$new_node->uid = $user->uid; //you can specify some other userID here if you want
$new_node->name = $user->name;
$new_node->title = $YOUR_NODE_TITLE;
$new_node->body = $YOUR_NODE_BODY;
$new_node->status = 1; // published
node_save($new_node);

The function node_save() does a few things behind the scene. It checks if the nid property is empty to determine if this is a new insert or an update, then calls the appropriate functions so that you would not have duplicates. Put simply, if you want to do an update, populate the nid, and leave it out otherwise.

Creatnig a node with CCK fields involves this additional line (for each field):

$new_node->field_your_field[0]['value'] = $YOUR_FIELD_DATA;

Point to note is the [0]['value'], because CCK treats each field as multiple-value fields even if you specified otherwise in the field settings. If you see the error Fatal error: Cannot unset string offsets in …/modules/cck/content.module on line 1248, you’re probably missing the [0]['value'] and setting the value directly into $new_node->field_your_field.

To create a node with location, we need to save the location first to get a location ID before saving it along with our node:

$location = array(
'street' => $address,
'postal_code' => $postal,
);
$locationID = location_save($location);
$new_node = new stdClass();
// ... the usual stuff ...
$new_node->locations[0]['lid'] = $newLocationId;
node_save($new_node);

There you go. Another method is to manually craft an array to simulate a $_POST from a drupal form. To do that you basically have to know the form structure, populate the require fields and pass the array on to the drupal_execute() call. Refer to the example here for more details.

Drupal references:
Node_save: drupal documentation

Comments

Popular posts from this blog

Privacy Policy - StoryScribe

Privacy Policy - aXa Voice Command Assistant

StoryScribe