light9
1/22/2015 - 7:34 AM

Programmatically Create Field Collections in Drupal http://devblog.com.au/programmatically-create-field-collections-in-drupal

Programmatically Create Field Collections in Drupal http://devblog.com.au/programmatically-create-field-collections-in-drupal

<?php 
/**
 * Creates a field collection.
 *
 * @param $parent
 * @param $type
 * @param $collection_name
 * @param $values
 * @return object
 */
function _module_name_add_field_collection($parent, $type, $collection_name, $values) {
 
  // Create entity using the entity name and set the parent.
  $field_collection_item = entity_create('field_collection_item', array('field_name' => $collection_name));
  $field_collection_item->setHostEntity($type, $parent);
 
  // EMW makes it easier for us to work with the field_collection
  $field_collection_item_w = entity_metadata_wrapper('field_collection_item', $field_collection_item);
 
  // Add the fields to the entity.
  foreach($values as $key => $value) {
    $field_collection_item_w->{$key}->set($value);
  }
 
  // Save the entity.
  $field_collection_item_w->save();
 
  return $field_collection_item;
}
?>