How to check for previous value when saving a node in Drupal

How to check for previous value when saving a node in Drupal

When you save a node in Drupal 7, hook_node_presave is there to modify values before the node is saved. Also available are the ‘original’ values so you can compare values from before the edit to after the edit. Can come in handy if you need to trigger some processes when values are changed (only when changed, not on every save) or if you have conditional fields based on other fields’ values.

function mymodule_node_presave($node) {
  if ($node->type == 'my_content_type') {
    if ($node->title != $node->original->title) {
      // the title has changed, do something
    }
  }
}

You can see the original node values are stored in $node->original, so it’s easy to compare two values to see if any changes were made.

Comments are closed.