Loading Only One Field From An Entity or Node in Drupal 7

Time from time, while doing your custom Drupal code, you may want to load only one or several specific fields from a defined set of entities.

So actually you have three approaches to this:

1. Query for entity/node set and load whole entities to get desired fields data. Works, but not a performant solution.

2. Make a direct sql query and get desired fields out of your database. Works too, is the fasted in terms of performance solution, but not too flexible and portable.

3. Leverage EntityFieldQuery() and field_attach_load(). This approach is not as fast as the second, but way more faster than loading whole nodes, it is flexible and uses field caching mechanism. If you'll decide to change your database backend later in the future, let's say to MongoDB, you'll be able to switch without changing a line in your code, neat! But the biggest thing I love about the following approach is that you don't care if you field is single valued or multivalued. You'll get all the values without too much hassle.

So let's get in more details. EntityFieldQuery() allows finding entities based on entity properties (for example, node->changed), field values, and generic entity meta data (bundle, entity type, entity id, and revision ID). More details about what EntityFieldQuery() can do for you find in official docs here: http://api.drupal.org/api/drupal/includes%21entity.inc/class/EntityFieldQuery/7

Now let's imagine a sample task. We'll need a list of image urls of image fields attached to nodes of type "Story". So how do we get this list? Simple, watch my moves:

1. Let's use EntityFieldQuery() to query a list of our article nodes:

1
2
3
4
5
6
  1. $query = new EntityFieldQuery();
  2. $query->entityCondition('entity_type', 'node')
  3. ->entityCondition('bundle', 'story')
  4. ->propertyCondition('status', 1)
  5. ->fieldCondition('field_story_image', 'fid', 'NULL', '!=');
  6. $result = $query->execute();

So we queried for a list of nodes of type "story" and made sure that node has image attached to it. Imagine yourself doing this query via raw sql. $result should return us a list of entity ids. Node ids should leave in $result['node']:

1
2
3
  1. if (isset($result['node'])) {
  2. $stories = $result['node'];
  3. }

Yes, we have to check if we have $result['node'] is set, because EntityFieldQuery() returns empty array in case if didn't find any nodes.

2. Now to the most interesting part. Okay, we have an array of node ids, so now we want to load only 'field_story_images' for these nodes. We'll use field_attach_load() to do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
  1. if (isset($result['node'])) {
  2. $stories = $result['node'];
  3. // At first we need to get field's id. If you already know field id, you can ommit this step
  4. // Get all fields attached to a given node type
  5. $fields = field_info_instances('node', 'story');
  6. // Get id of body field
  7. $field_id = $fields['field_story_image']['field_id'];
  8. // Attach a field of selected id only to get value for it
  9. field_attach_load('node', $stories, FIELD_LOAD_CURRENT, array('field_id' => $field_id));
  10. }

I described what we're doing in each step in the code, so everything should be pretty much understandable. In the end, we're getting $stories array, which holds "semi-loaded" nodes with only field we queried attached. Caveat. field_attach_load() doesn't invoke hook_node_load(), so if some data is being manipulated via hook_node_load() you won't get its representation via described method. This is the only drawback of this method. But in most cases it is safe to use. Just check if it works in your situation.

3. To access your list of values you can do the way you access full node's values, something like this:

1
2
  1. // Get values of our node field
  2. $output = field_get_items('node', $node, 'field_story_image');

UPDATE: I wrote a more detailed tutorial on how to access node fields values: Working with Drupal Fields: Getting Single Field Values For Display and Manipulaton. That simple! So for those who could get lost, here's the full code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  1. $query = new EntityFieldQuery();
  2. $query->entityCondition('entity_type', 'node')
  3. ->entityCondition('bundle', 'story')
  4. ->propertyCondition('status', 1)
  5. ->fieldCondition('field_story_image', 'fid', 'NULL', '!=');
  6. $result = $query->execute();
  7. if (isset($result['node'])) {
  8. $stories = $result['node'];
  9. // At first we need to get field's id. If you already know field id, you can ommit this step
  10. // Get all fields attached to a given node type
  11. $fields = field_info_instances('node', 'story');
  12. // Get id of body field
  13. $field_id = $fields['field_story_image']['field_id'];
  14. // Attach a field of selected id only to get value for it
  15. field_attach_load('node', $stories, FIELD_LOAD_CURRENT, array('field_id' => $field_id));
  16. // Get values of our node field
  17. $output = field_get_items('node', $stories, 'field_story_image');
  18. }

UPDATE: put this snippet on dropbucket for future reference: http://dropbucket.org/node/54 As you see, the described approach is pretty neat, you get all values of a field in one go and you leverage Drupal cache mechanism. More over, if you want to query for several fields, you need to add just two more lines to our code, let's say, in addition to image fields we want to get a body field, so after:

1
2
3
4
5
  1. // Get id of body field
  2. $field_id = $fields['field_story_image']['field_id'];
  3. // Attach a field of selected id only to get value for it
  4. field_attach_load('node', $stories, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

you just need to add:

1
2
3
4
5
  1. // Get id of body field
  2. $field_id = $fields['body']['field_id'];
  3. // Attach a field of selected id only to get value for it
  4. field_attach_load('node', $stories, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

And you'll get a body field attached too! Or in more cleaner way these two fields attachment could look like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
  1. // Get all fields attached to a given node type
  2. $fields = field_info_instances('node', 'story');
  3. // Put all field names you want to load
  4. $field_names = array('field_story_image', 'body');
  5. foreach ($field_names AS $field_name) {
  6. // Get id of body field
  7. $field_id = $fields[$field_name]['field_id'];
  8. // Attach a field of selected id only to get value for it
  9. field_attach_load('node', $stories, FIELD_LOAD_CURRENT, array('field_id' => $field_id));
  10. }

Wow that was a long read, but if you've survived till the end this means that now you have a powerful tool in your skillset. Go and try it!