Skip to content

Instantly share code, notes, and snippets.

@danbruder
Last active December 22, 2015 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danbruder/6437763 to your computer and use it in GitHub Desktop.
Save danbruder/6437763 to your computer and use it in GitHub Desktop.
Programmatically adding a field collection item to a node
<?php
function my_function_name_add_image_to_field_collection($nid, $fid){
// Load target node
$node = node_load($nid);
// Create a new field collection
$field_collection_item = 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
$field_collection_item->field_image[LANGUAGE_NONE][] = $file;
$field_collection_item->field_link[LANGUAGE_NONE][] = $link;
// Save field collection item
$field_collection_item->setHostEntity('node', $node);
$field_collection_item->save(TRUE);
node_save($node);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment