0

I need to trigger some logic to recalculate certain computed fields based on what fields may have been altered when a user updates a node. So I'm looking to create a function that returns a list of of fields the user has updated.

I've come pretty far by using hook_node_update().

Currently the process is like this.

My hook_node_update looks roughly like this:

function hook_node_update($node) {
  $old_node = node_load($node->nid);

  // Figure out what fields have been altered.
  $altered = _get_altered_fields($node, $old_node);

  // Recalculate the fields *after* node save.
  drupal_register_shutdown_function('_process_fields', $node, $altered);
}

And the _get_altered_fields function:

function _get_altered_fields($node, $old_node) {

  $changed = array();

  if ($old_node-> field_somefield != $node-> field_somefield) {
    $changed[] = 'somefield';
  } elseif ($old_node-> field_someotherfield != $node-> field_someotherfield) {
    $changed[] = 'someotherfield';
  }

  return $changed;
}

The problem with the above is that I get 'false positives' (i.e. 'someotherfield' gets registered as changed even though it is not) because the $node object does not have the exact same data structure as $old_node, which was fetched from the database. In general $node has more attributes - especially if it is a taxonomy field - such as 'vid', 'weight' and 'rdf_mapping'.

I tried creating a normalize function where I unset those attributes, but it gets very messy. I figure someone must have done this before me. Any suggestions how to do this in a clean way?

0

The simple way of recalculating and update field without any effect of other field is hook_entity_update or code like display here.

<?php
$entity_instance = entity_load('entity_name', array($id));
$entity_instance->field_myfield[LANGUAGE_NONE][0]['value']= 5;
$entity_instance->save();
?>
  • I don't really have a problem recalculating the fields. The problem is reliably determining what fields have been updated, as apparently the $node object available in hook_node_update() and the node object I can fetch with node_load() are not consistent. But maybe entity_load will give me the fields that I miss with node_load(). I suppose it is worth a shot. – funkylaundry Aug 24 '15 at 13:13
  • D7 is based on entity so it is worth of using hook_entity functions against hook_node. – vgoradiya Aug 24 '15 at 13:30
  • I found this thread, where the general opinion seems to be that node_load() is fine as long as you know the entity you are querying will be a node, which I do in this case: drupal.stackexchange.com/questions/5764/… – funkylaundry Aug 24 '15 at 13:40

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.