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.

Comments

Required for comment verification



Vineet Bhardwaj

Thanks :-) Great help

Reply · 1 year, 2 months ago
Jürgen

Thanks for sharing, it did save me from pulling more hair! ;-)

Reply · 5 years, 2 months ago
Pedro

Hi, is also posible to change the field value from a field inside a field collection? Thanks

Reply · 5 years, 2 months ago
barnettech

Yes I was pulling out my hair for 2 minutes. Thank you for putting an end to my stress with this post. :)

Reply · 5 years, 2 months ago
nelson

Thanks!! I don't have that much hair left to waste!!

Reply · 5 years, 2 months ago
konopko
field_attach_update('node', $node);

calls error but realy save changes, better use hook_node_presave

Reply · 5 years, 2 months ago
patrickd

Note that field_attach_update() always expects all fields! If you just pass it the fields you actually want to update it will drop others like image or file fields. This is 'by design'.

Reply · 5 years, 2 months ago