Web design, programming, graphics, and pretty much anything else I care about.

Programmatically inserting nodes

Inserting nodes, programmatically, is not always the easiest thing. The "drupally" way of doing it is to build the node form array and then submit it to drupal_execute(). (http://api.drupal.org/api/drupal/includes--form.inc/function/drupal_exec...) This follows the same procedure that the node/add form follows. This method will make sure that all the same validations occur, permission checks, etc. The problem is this is a slow process, and some modules don't work well with drupal_execute; namely, Date. To insert modules that have date fields, use node_save().

This will skip a lot of the validation that drupal_execute will perform, so make sure you check your data before inserting it.

The following code was used to insert data that represented calendar events. An array is first created called $event, and populated with all the field data (not shown.) To keep track of data from an outside system, I used a CCK field ($node->field_event_id) to keep track of the id from the non-Drupal system. The first step is to look up the event id in CCK and see if it already exsits. If so, get the associated Drupal node id. Finding this information will determine if a new node is created, or an existing node is updated.

<?php
$node
= new StdClass();

// These lines are for CCK.
// Get the Drupal field and table info.
// We need to do this because the content type might have been altered.
$field_info = content_fields('field_event_id', 'my_content_type');
$db_info = content_database_info($field_info);
$table_name = $db_info['table'];
$column_name = $db_info['columns']['value']['column'];

// Check to see if this node already exists in Drupal.
// If it does, add the node id so that node_save() will do an update.
if ($exists = db_fetch_object(db_query('SELECT DISTINCT nid, vid FROM {%s} WHERE %s = %d', $table_name, $column_name, $event->event_id))) {
 
$node->nid = $exists->nid;
 
$node->vid = $exists->vid;
}
$node->type = 'my_content_type';
$node->uid = 1;
$node->title = $event->title;
$node->body = $event->description;
$node->field_event_id[0]['value'] = $event->event_id;
$node->field_speaker[0]['value'] = $event->speaker;
$node->field_affiliation[0]['value'] = $event->affiliation;
$node->field_location[0]['value'] = $event->location;
$node->field_start = $event->dates;

// Build an array of taxonomy terms.
$node->taxonomy = array();
foreach (
$event->terms as $term_id) {
 
$node->taxonomy[] = taxonomy_get_term($term_id);
}

node_save($node);
?>