Last Updated: February 25, 2016
·
576
· darkflames

Get your node field_collection easy

In the first time I had to use field collection in drupal 7, I've thought that my field collection fields and values would be directly avaliable on the the $node in my node.tpl.php. Sadly it wasn't how i thought, you have to load the entity and then get your fields. It was kind of tricky for me at first, but then I've built a function that can do all the job for me in an easy way.

/**
* search all your field_collection
* @param $node the loaded node
* @param $collection the machine name of your field collection
* @return array of objects FieldCollectionItemEntity
*/
function getFieldCollection($node, $collection) {

    foreach($node->{$collection}[LANGUAGE_NONE] as $collectionItem) {
        $entity = entity_load('field_collection_item', array($collectionItem['value']));
        $fieldCollection[] = $entity[(int)$collectionItem['value']];
    }

    return $fieldCollection;

}

That way, all you have to do is call this function and loop through the collection to get your field as you always do in the node.

$myCollection = getFieldCollection($node, 'field_collection_name');
foreach($myCollection as $collection) {
    $myFieldValue = $collection->field_collection_field['und'][0]['value'];
}

if you want to look through the field_collection api here is the link for the Understanding Field Collection Values
http://drupal.org/node/1477202

Hope that it helps