Update CCK Fields In Custom Drupal Nodes
boz — Tue, 06/22/2010 - 13:17
This Post Has Been Updated From The Original : See Bottom
This was a major hang up on my recent project. I thought I would share in hopes of saving someone else sometime. The explanation for the code being this tedious has to do with CCK's database structure. Each field is given its own table, so to avoid costly queries CCK has a database cache. Here is the code. I had to read through several other posts to find this. I'll try to link to those when I get time.
// Load node to edit
$node = node_load($your_node_id);
// Index value of the cck field
$index = 0;
// value that you want to insert
$new_value = 3;
// Set value
$node->field_your_field[$index] = array('value' => $new_value);
// Save Node
node_save($node);
// Update content if node exists, otherwise use content_insert()
content_update($node);
// Clear CCK data cache so the new value will be loaded for dispaly purposes
db_query("DELETE FROM {cache_content} WHERE cid = '%s'", 'content:' . $node->nid . ':' . $node->vid);
Update:
Since writing this new things have come to light. While the code above works. It is overkill simply saving a CCK field. Also, there are more than one scenario for updating.
Scenario 1: node_save
// Load node to edit
$node = node_load($your_node_id);
// Index value of the cck field (Depends on the number of values your field accepts)
$index = 0;
// Set value
$node->field_your_field[$index] = array('value' => $new_value);
// Save Node
node_save($node);
node_save runs cache_clear_all() so you don't need to delete a row from CCK cache.
Scenario 2: db_query
// Load node to edit
$node = node_load($your_node_id);
// Index value of the cck field (Depends on the number of values your field accepts)
$index = 0;
// Save Node
db_query('UPDATE {content_type_x} SET field_y="%s" WHERE vid="%s" AND nid="%s"', $new_value, $node->vid, $node->nid);
// Clear CCK data cache so the new value will be loaded for dispaly purposes
db_query("DELETE FROM {cache_content} WHERE cid = '%s'", 'content:' . $node->nid . ':' . $node->vid);

Thanks for sharing. I'd also
Anonymous — Fri, 01/27/2012 - 14:30- node_save() invokes hook_nodeapi, updates node->changed, etc. which you may or may not want in your custom implementation.
- In your simpler scenario 2, looks like the $index line is unused
-BroniusWhy are you using node_submit
Anonymous — Sat, 03/12/2011 - 13:02Good to know. For my
Anonymous — Sat, 03/12/2011 - 17:07Simply omit this line: $node
Anonymous — Mon, 03/14/2011 - 07:20$node = node_submit($node);node_submit is only needed when you are building a new node object.Thanks!
Anonymous — Wed, 09/29/2010 - 12:57