Skip to main content

Loading Field Collections

Submitted by on Mon, 08/03/2015 - 16:52

The Field Collection module for Drupal 7 is a very handy way to attach groups of fields to nodes. If you are a regular D7 dev and do not know it, check it out, i´m sure you´ll find it very useful. That being said, it can be a bitch to load the Field Collcetions attached to nodes programmatically.

The “wrong” way

The obvious way to load a field collection, would be with entity_load:

<?php
$node = node_load($nid);
$items = field_get_items('node', $node, 'field_collection');

foreach ($items as $item) {  
  $field_collections = entity_load('field_collection_item', array($item['value']));  
  $field_collection = array_shift($field_collections);  
  // Do stuff with your field collection entity.
}
?>

And this might actually work. The only problem is, the Field Collection module makes heavily use of revisions, so when you at some point update the value of the field collection on the node, you might not get the right value in your code.

The right way

Luckily the field_collection_field_get_entity can solve this little revision obstacle:

<?php
$node = node_load($nid);
$items = field_get_items('node', $node, 'field_collection');

foreach ($items as $item) {  
  $field_collection = field_collection_field_get_entity($item);
  // Do stuff with your field collection entity.
}
?>

So not only is it one line shorter (!), you also always get the right, expected value.

Comment? Tweet me