How To Save Yourself Some Hair When Manipulating Node Fields

03 Oct · by Tim Kamanin · 2 min read

Ok, you're clever guy/girl and don't use some generic modules like computed field, right? And you want to change some node field data based on your conditions, right? What will you do? Of course, write your manipulation using hook_node_presave(), but there are some circumstances, when this hook won't work (for example, you need a node id for a "to be created" node, which isn't available in hook_node_presave()) and you will have to deal with hook_node_insert() and hook_node_update(), so what will you do then? "Treat it like hook_node_presave()" - you will say and here you're going to be wrong. Here's where the pain begins and I'll tell you how to omit it.

Say your fantasy data manipulation might look like:

/**
*  Implements hook_node_insert()
*/
fancy_module_node_insert($node) {
  $node->field_my_special_copy_of_nid[$node->language][0]['value'] = $node->nid;
}

And, as in the case of hook_node_presave(), you're supposed to be done, your field_my_special_copy_of_nid *should get a node id as a value on a node insert. Right? Wrong! The thing is, *$node won 't get affected (same applies to hook_node_update() case) by your changes until you add field_attach_update('node', $node); to the end of the hook, so it looks like:

/**
*  Implements hook_node_insert()
*/
fancy_module_node_insert($node) {
  $node->field_my_special_copy_of_nid[$node->language][0]['value'] = $node->nid;
  field_attach_update('node', $node);
}

Not diving deep into details, this is how Drupal's 7 Field Api works, you need to update field attachments when you manipulate their values in hook_node_insert() and hook_node_update() hooks. Just be aware of that. Hope this will save time for someone.

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials

Comments