Using drupal 7 field collection programmatically

Insert field collection

//Create the Field Collection entity
$item = entity_create('field_collection_item', array('field_name' => 'myfieldcoll_machine_name'));
//set the hosting node 
$item->setHostEntity('node', $myNode_object);

//Fill your fields
$item->field_myfield[LANGUAGE_NONE][0]['value'] = 'My Value;

//Save the entity
$myNode_object->myfieldcoll_machine_name[LANGUAGE_NONE][]['value'] = $item->item_id;

Update field collection

//Load the Field Collection entity
$item = entity_load_single('field_collection_item', array($item_id));
//Update your fields
$item->field_myfield[LANGUAGE_NONE][0]['value'] = 'My Value;

//Save the entity

Delete field collection properly

entity_delete_multiple('field_collection_item', array($field_collection_item->item_id));

//Sometimes the field collection item remains in the node, so you have to clean that.

So, to delete a field collection of a specific node

$node = node_load($node_id);
$field_collection_item_value = array();
foreach ($node->field_collection_field[LANGUAGE_NONE] as $key => $value) {
    $field_collection_item_value[] = $value['value'];
entity_delete_multiple('field_collection_item', array($field_collection_item_value));

However, deleting field collections would not remove their entries from the node where they are referenced, hence the nodes would provide log of the field collection object not being available when Drupal tries to load the deleted reference. Hence a small code snippet below becomes handy in resolving this issue:

$node = node_load($node_nid);
foreach($node->field_collection_field[LANGUAGE_NONE] as $key=>$value) {
  $fc =  entity_load_single("field_collection_item",$value['value']);
    print $value['value']." does not exist \n";

Leave a Comment.