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
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
And here's how to use it on practice:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
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.