Programmatically Adding a Field Collection Item to a exiting Node in Drupal

In such case where you need to add field item to a node like text,link field's in a node for drupal 7


function my_custom_module_field_collection($nid, $fid){
   // Load target node
   $node = node_load($nid);

   // Create a new field collection 
   $fieldCollectionItem = entity_create('field_collection_item', array('field_name' => 'my_field_collection_item_name'));

   // Prepare link field
   $link = array(
      'title' => "",
      'url' => "",
      'attributes' => array(
         'title' => "",
      ),
   );

   // Prepare file 
   $file = (array)file_load($fid);
   $file['display'] = "1";

   // Load items into field collection
$fieldCollectionItem->field_image[LANGUAGE_NONE][] = $file;

$fieldCollectionItem->field_link[LANGUAGE_NONE][] = $link; // Save field collection item

$fieldCollectionItem->setHostEntity('node', $node);

$fieldCollectionItem->save(TRUE); node_save($node);
 
}

 

Advertisements