Loading only single field from an entity or a node


Get raw version
  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();
  8. if (isset($result['node'])) {
  9. $stories = $result['node'];
  11. // At first we need to get field's id. If you already know field id, you can ommit this step
  12. // Get all fields attached to a given node type
  13. $fields = field_info_instances('node', 'story');
  15. // Get id of body field
  16. $field_id = $fields['field_story_image']['field_id'];
  18. // Attach a field of selected id only to get value for it
  19. field_attach_load('node', $stories, FIELD_LOAD_CURRENT, array('field_id' => $field_id));
  21. // Get values of our node field
  22. $output = field_get_items('node', $stories, 'field_story_image');
  23. }


hook_drupal's picture

Niestety w snippet wkradł się mały błąd. Zmienna $node w lini 22 nie ma zupełnie racji bytu.

timonweb's picture

Racja, powinno być $stories, naprawiłem, tx.

ooops's picture

@tim I am not sure but I think $stories will be an array and field_get_items() expect a single $entity as argument, it may through an exception in that case.Isn't?

ooops's picture

How about making a small change something like this

  1. // Let say we need field value for a particular nid
  2. // Assume $nid is that node id
  4. //then the small change comes in the last line
  5. // Get values of our node field
  6. $output = field_get_items('node', $stories[$nid], 'field_story_image');