How To Insert and Update Only Specific Fields Of Your Entity In Drupal 7

Time from time you need to update single or several specific fields of your entity in Drupal. It can be node, comment, taxonomy or some other custom entity. So how do we usually do this? Let's see:

1
2
3
4
5
6
7
  1. $node = node_load(1); // 1 is node id we want to load
  2. // Change field value
  3. $node->field_product_description[$node->language][0]['value'] = 'This is a very nice and useful product. Buy it now! We want your money!';
  4. // Save updated node
  5. node_save($node);

This approach is totally ok, but hey, your poor Drupal did a massive job to update just one field: it loaded the whole node into memory and then, saved every field (even which wasn't updated) one by one into database. If your nodes are pretty big, it can produce a lot of unnecessary queries.

Here's how to update entity field in a more "diet" way by using Drupal 7 Field API, this is a general code template:

1
2
3
4
5
6
7
8
9
  1. // Get the numeric id of your field by passing field name
  2. $info = field_info_field('field_name_goes_here');
  3. $fields = array($info['id']);
  4. // Execute the storage function
  5. field_sql_storage_field_storage_write('entity_type', $entity, 'update', $fields);
  6. // Clear field cache
  7. cache_clear_all("field:$entity->type:$entity->id", 'cache_field');

And here's how to use it on practice:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
  1. $node = node_load(1); // 1 is node id we want to load
  2. // Change field value
  3. $node->field_product_description[$node->language][0]['value'] = 'This is a very nice and useful product. Buy it now! We want your money!';
  4. // Get the numeric id of your field by passing field name
  5. $info = field_info_field('field_product_description');
  6. $fields = array($info['id']);
  7. // Execute the storage function
  8. field_sql_storage_field_storage_write('node', $node, 'update', $fields);
  9. // Clear field cache
  10. cache_clear_all("field:node:$node->nid", 'cache_field');

So now, we updated only one field of the node without updating the whole node. Please note, that you can pass as many fields as you like via $fields array, so you can update more than one entity field at once.

That's all for now, thanks for reading this. Share with others!

A VERY BIG NOTE: Using this technique you can't rely on drupal hooks system. No hooks are being invoked, updated nodes won't be queued for search indexing if you won't do this manually. Be awared.