2

I would like to programmatically update some fields including the title of a node, when this node is saved. To do so I am using a hook

function MY_MODULE_node_update($node) {
    $node->title = "Something new an beautiful";
    $node->filed_what_ever = "Something";
    field_attach_update('node', $node);
}

The problem is, that the title is not updated, I assume, that's because of the fact it isn't a field an the Drupal sense. But I can not use

node_save($node);

instead, because that brings me in an infinite loop: the function hook_node_update() is called by the function node_save()... So what would be a clean why to do this?

  • You should probably use a hook that gets called earlier in the node updating process. I think adding a custom submit handler in a hook_form_alter(), that changes the node title before save, might work. – beth Jan 29 '13 at 23:13
6

To do this, you have to use hook_node_presave().

It's called before saving the node to the database. (both new nodes and edits). Note that you must make sure that you are saving sanitized and formatted data.

  • Does that mean, with hook_node_presave() I just can set or alter the fields as I wish, and than they will be saved without having to call field_attach_update() or node_save() again? – user5950 Jan 29 '13 at 23:28
  • exactly! You don't need to return the node. it will be passed by reference so go ahead and make the changes. – AyeshK Jan 29 '13 at 23:32
  • The only way to change programmatically the node title is in the hook_node_presave? – Adrian Cid Almaguer May 4 '16 at 12:37
  • @AdrianCidAlmaguer with the context of original question about using a hook_node_update, you will have to use the presave hook or save the node yourself. – AyeshK May 4 '16 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.