If you have use Field-Collection module (http://drupal.org/project/field_collection), you would know how useful it is when you need to create a node with grouped value. However, due to how field-collection utilizes Entity API, you will not be able to programmatically update its value directly. Here's a great example on how you could do so:

Suppose 'field_page_collection1' is the field collection for the 'page' content type having two text fields 'field_page_collection1_text1', 'field_page_collection1_text2'.


To attach or create field-collection item for node having node id 1:

$node = node_load(1);

$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_page_collection1')); // Create new field collection item.

$field_collection_item->setHostEntity('node', $node); // Attach it to the node.

$field_collection_item->field_page_collection1_text1[LANGUAGE_NONE][0]['value'] = 'some value for text field 1'; // Fill value for field_page_collection1_text1.
$field_collection_item->field_page_collection1_text2[LANGUAGE_NONE][0]['value'] = 'some value for text field 2'; // Fill value for field_page_collection1_text2.

$field_collection_item->save(); // Save field-collection item.

To modify/update values from existing field collection item of node having node id 1:

$node = node_load(1);

$field_collection_item_value = $node->field_page_collection1[LANGUAGE_NONE][0]['value']; // Get field collection item value.
$field_collection_item = entity_load('field_collection_item', array($field_collection_item_value)); // Load that field collection item.
$field_collection_item->field_page_collection1_text1[LANGUAGE_NONE][0]['value'] = 'updated value for text field 1'; // Update value for field_page_collection1_text1.
$field_collection_item->field_page_collection1_text2[LANGUAGE_NONE][0]['value'] = 'updated value for text field 2'; // Update value for field_page_collection1_text2.
$field_collection_item->save(); // Save field-collection item.

To delete existing field collection item for node having node id 1:

$node = node_load(1);

$field_collection_item_value = $node->field_page_collection1[LANGUAGE_NONE][0]['value']; // Take field collection item value.
entity_delete_multiple('field_collection_item', array($field_collection_item_value)); // Delete field collection item.

 

Source: http://rajanmayekar.com/blog/programmatically-creating-deleting-modifyi…

Published on 10 May 2012 - 8:19pm