When a field collection is added to a user, node, or other Drupal entity it is represented with a field type of field_collection_item. The value stored in the field_collection_item field is the id of the field collection, not the individual values of the fields making up the field_collection_item.

For example, take the following configuration:

  • Node type Playlist
  • Playlist has a field collection named Track (field_track)
    field_track of type field collection
  • Track field collection consists of the fields Song and Artist
    field_song of type text
    field_artist of type text

A Playlist node is created with two tracks. For the purposes of the example the following values are assigned:

  • Playlist node id: 25
  • 1st track: field_collection id: 17
    field_song: The Drupal Song
    field_artist: Lullabots
  • 2nd track: field_collection id: 18
    field_song: Drupal Heaven (I Shall Be Released)
    field_artist: The Secret Kitten Killers

When node 25 is loaded, field_track has the following value:

[field_track] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] => 17
                    )
                [1] => Array
                    (
                        [value] => 18
                    )
            )
    )

To get the values of the individual field items call the entity_load function:

  $node25 = node_load(25);
  $track_1 = entity_load('field_collection_item', array($node25->field_track[LANGUAGE_NONE][0]['value']));
  $track_2 = entity_load('field_collection_item', array($node25->field_track[LANGUAGE_NONE][1]['value']));

Comments

ro-no-lo’s picture

According to the function signature. The second parameter of entity_load(..., array($id)); needs to be an array of IDs. There is no check if just a numerical value is given. So, wrap a single argument in array() to make this example work.

zarexogre’s picture

The error is Fatal error: Unsupported operand types in /home/tim/Projects/fba/htdocs/includes/entity.inc on line 354

and yes best to put in array

$comp = entity_load('field_collection_item',array(1));

Great work by the way!

crabsoul’s picture

here comes working version to render field collection fields one by one. here "field_references" is my field collection name which has two fields, named as "field_reference_title" and "field_reference_location".

Below is code snippet for how to print field collection in node.tpl file.

  $wrapper = entity_metadata_wrapper('node', $node);
  $formtype = field_get_items('node', $node, 'field_references');
   foreach($formtype as $itemid) { 
              $item = field_collection_field_get_entity($itemid);
             print $item->field_reference_title['und'][0]['safe_value'];
             print $item->field_reference_location['und'][0]['safe_value'];

}

Enjoy!!!!! :)

misthero’s picture

is it possible to have an alternative to:

$item->field_reference_title['und'][0]['safe_value'];

without having to specify the ['und'] language?

ro-no-lo’s picture

You have to iterate through the langcodes then. Btw. there is a global Constant: LANGUAGE_NONE.

ChrisValentine’s picture

$item = field_collection_field_get_entity($itemid);

field_collection_field_get_entity doesn't exist in the API.

Web application developer
http://kmi.open.ac.uk/

i32orgrr’s picture

It work for me but if the field it's an imagen the imagen don't show, any idea?

harikris2007’s picture

helped me.thank you.

sumithra ramalingam’s picture

It Works for me. Thank you lot :)

hondaman900’s picture

Thank you for this great example. However I'm getting an error with the above code I can't trace. My entity metadata wrapper works fine, but the reference to the field collection is throwing an error that's not really telling me anything helpful.

Here's my code:

	$wrapper = entity_metadata_wrapper('entityform', $entityform); // this wrapper works fine, can extract field data

	dpm(_wrapper_debug($wrapper));  //debug code from EMW page* on drupal.org

	$formtype = field_get_items('entityform', $entityform, 'field_inv_account_details');
		foreach($formtype as $itemid) { 
					 $item = field_collection_field_get_entity($itemid);
					 print $item->field_inv_line_item_name['LANGUAGE_NONE'][0]['safe_value'];
					 print $item->field_inv_item_value['LANGUAGE_NONE'][0]['safe_value'];

		}

This gives error:

EntityMalformedException: Missing bundle property on entity of type entityform. in entity_extract_ids() (line 7922 of C:\wamp\www\mysite\includes\common.inc).

Not sure what's causing the error. Also, in your example, is the wrapper line necessary? It doesn't seem to be referenced in the rest of the code.

* _wrapper_debug code from EMW info page

kaizerking’s picture

I wanted to get all the terms in field collection fields,attached to profile2 of an user the following code is throwing Entity malfunction exception error can some one help me please

<?php
$user_fields = field_get_items('field_collection_item', $account, $field_name);
		if (!empty($user_fields)) {
			foreach ($user_fields as $term) {
				$user_terms[$field_name][$term['tid']] = TRUE;
?>
khaljava’s picture

Create by AJAX post like it in http://drupal.org/node/1354202

{
   "field_collection":[
      {
         "first_field":"100",
         "secondfield":"20"
      }
   ]
}
psychobyte’s picture

Hi,

I have a node that has field_collections. I would like to duplicate this node and it's field collection items. If I just did a straight duplication of the node by removing the nid value and saving the node object. this will probably replicate the field collection items however, i need to generate new field collections identical in data but, unique as field collection items go.

Is there a proper way of doing this?

Thanks.

zorax’s picture

I try to update a collection field, but can't save the field.
I need to update the field when the user save the node so I use hook_node_update

dpm($node);
	// Get field collection item value.
	$field_collection_item_value = $node->field_pistes_de_projets_explorer['und'][1]['value'];
	dpm($field_collection_item_value);
	// Load that field collection item
	$field_collection_value = entity_load('field_collection_item', array($field_collection_item_value)); 
	dpm($field_collection_value);
	$field_collection_value[184]->field_projet_total['und'][0]['value'] = 25;
	dpm($field_collection_value);
	//and we can call after save but chrome is waiting....
	$field_collection_value[184]->save();

I try with a second method :

$wrapper = entity_metadata_wrapper('node', $node);
$formtype = field_get_items('node', $node, 'field_pistes_de_projets_explorer');
	
foreach($formtype as $itemid) {
          $item = field_collection_field_get_entity($itemid);
	 dpm($item);
         $item->field_projet_total['und'][0]['value'] = $item->field_realisable['und'][0]['value'] + $item->field_desirable['und'][0]['value'];
	dpm($item->field_projet_total);
	}
	
	$wrapper->save(true);
hacmx’s picture

Hi Zorax!,you could found a solution to this?, sorry for comment after a long time but i have similar code like you. I hope you could help me. Thank you!.