Programmatically Save Field Collection in Drupal

Below you will find a quick snippet example of how to save a field collection programmatically in Drupal 7.

/**
 * Save New Field Collection
 */
$field_collection = array(); // new array
$field_collection['field_name'] = 'field_collection_field_name'; // field collection machine name
$field_entity = entity_create('field_collection_item', $field_collection); // create entity in system

$field_entity->field_value[LANGUAGE_NONE][0]['value'] = 'Test Value'; // add fields
$field_entity->setHostEntity('node', $host_entity); // set host entity, in this case a node
$field_entity->save(); // save the entity to set it to the parent node

Add new comment