How to edit a node programatically after it has been created? My articles have a field 'Ranking' and I'd like to give a value to this field after a node has been created. The value depends on the node's ranking in a view called 'Top 3'. I tried the following in my custom module 'Top', but it doesn't work.

function top_node_insert($node) {
  $top = views_get_view_result('top_3');

  $found = false;  
  foreach($top as $key =&gt; $value) {
    if ($value-&gt;nid == $node-&gt;nid) {
        $found = true;
        break;
    }
  }

  if ($found) $ranking = $key + 1;
  $node-&gt;field_hoogste_ranking[LANGUAGE_NONE][0]['value'] = $ranking;
}


What did I do wrong and what's the correct version?
If you look at the Node API Hooks description here, you will see that hook_node_insert is called after field_attach_insert. That means that at the point hook_node_insert is called the fields for the node are already written to the database. If you keep your code in top_node_insert, then add field_attach_update('node', $node) to update the fields with the new data. It might look something like this:

function top_node_insert($node) {
  $top = views_get_view_result('top_3');

  $found = false;  
  foreach($top as $key =&gt; $value) {
    if ($value-&gt;nid == $node-&gt;nid) {
        $found = true;
        break;
    }
  }

  if ($found) {
    $ranking = $key + 1;
    $node-&gt;field_hoogste_ranking[LANGUAGE_NONE][0]['value'] = $ranking;
    field_attach_update('node', $node);
  }
}


Alternatively, you can try and use hook_node_presave.