1

I wanted to update a field that is not seen by the user, but I would turn off and on (boolean) quite a lot (and for thousands of nodes). I initially used field_attach, but this had the unhappy effect of removing a file that was also attached to the node (this is a drupal bug).

It took a lot of searching, but I found the solution combining a couple of other peoples snippets. I put it below so hopefully may save someone some time.

For the record: Apparently it is bad practice to edit fields directly like this, however, I really needed to for this use case and I have yet to find any issues. You have been warned!

2
function common_update_db($entity_id, $field_name, $value, $clear_cache) {
  foreach (array('data', 'revision') as $table) {
    $result = db_update('field_'.$table.'_'.$field_name)
        ->fields(array(
            $field_name.'_value' => $value,
        ))
        ->condition('entity_id',$entity_id,'=')
        ->execute();
  }
  if ($clear_cache) {
    cache_clear_all("field:node:" . $entity_id, 'cache_field');
  }
}    

This will update the field and the revision field. If you send clear_cache = TRUE, it will also clear that nodes cache. This only works for *_value fields and nodes, but it's easy to modify.

Examples:

common_update_db(1234, field_run_cron, 1, TRUE);    

on node 1234, set field_run_cron value to 1 and clear the cache for immediate visible effect to the user.

common_update_db(1234, field_run_cron, 0, FALSE);    

on node 1234, set field_run_cron value to 0, don't clear cache as the user doesn't see this field anyway.

  • Thank you - this solution worked for me. I know you're not supposed to update a node's field in this way, but I haven't noticed any negative effects yet and node_save() is just not an option when dealing with > 1000 nodes. – Blake Frederick Jan 3 '18 at 21:33

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.