Field collections : CRUD (Create / Update / Delete) operations programmatically

With the entity system in Drupal 7 the fields has a real big value and what abuot a field which has number of fields tha we can manage inside it? Isn't that amazing? Drupal enetity system allows to create collection of fields as entity and make it work like a field. Wow!. Field Collection module is the succesor of that idea. Recently, I've been working on a drush script which clone nodes and update it's fields so programatiaclly update on the fields was required.


$field_collection_item = entity_create('field_collection_item', array('field_name' =>'field_text')); // Create new field collection item.
$field_collection_item->setHostEntity('node', $node); // This is required, there shuold be a host entity, this case I used a node.
$field_collection_item->field_text[LANGUAGE_NONE][0]['value'] = 'Test Value';
$field_collection_item->save(); // Save the field collection item.


$field_collection_item = field_collection_item_load($item_id); // Load that field collection item.
$field_collection_item->field_text[LANGUAGE_NONE][0]['safe_value'] = 'New value'
$field_collection_item->save(); // Save field-collection item.
entity_delete_multiple('field_collection_item', array($item_id)); // Delete field collection item.