I googled _create field_collection programmatically_ and this example was from my first search result.
Thought I would post my solution for programmatically creating a field collection, along with an attached field, during a module install. The example is specific to my use, but easily modified to add the field types you need. Of course, if there is an easier way please feel free to add your thoughts. This works with the current 7.x-1.x-dev branch.
/**
* Create a Field Collection field and attach collection node reference
*/
function _create_field_collection() {
$t = get_t();
$fields_array = array(
array(
'field' => array(
'field_name' => 'bir_collection',
'label' => $t('BIR Collection Nodes'),
'cardinality' => -1,
'type' => 'field_collection',
),
'instance' => array(
'field_name' => 'bir_collection',
'entity_type' => 'node',
'bundle' => 'article',
'label' => $t('BIR Collection Nodes'),
'description' => '',
'widget' => array('type' => 'field_collection_embed'),
'required' => 1,
),
),
array(
'field' => array(
'field_name' => 'bir_collection_node',
'type' => 'node_reference',
'label' => '',
'cardinality' => 1,
'settings' => array(
'referenceable_types' => array(
'bir_specimen' => 'bir_specimen',
'bir_image' => 'bir_image',
'bir_locality' => 'bir_locality',
'bir_view' => 'bir_view',
),
),
),
'instance' => array(
'field_name' => 'bir_collection_node',
'entity_type' => 'field_collection_item',
'bundle' => 'bir_collection',
'label' => '',
'cardinality' => 1,
'description' => '',
'widget' => array('type' => 'node_reference_autocomplete'),
'display' => array('default' => array('type' => 'node_reference_default')),
)
),
);
// Loop through fields array and create field and instance
foreach ($fields_array as $field) {
// Check if field already exists
if (!field_info_field($field['field']['field_name'])) {
field_create_field($field['field']);
}
// Check if instance exists
if (!field_info_instance($field['instance']['entity_type'], $field['instance']['field_name'], $field['instance']['bundle'])) {
field_create_instance($field['instance']);
}
}
}
First field in the $fields_array
array is the field_collection
type field that you add to your node
entity. (field_name: bir_collection)
The second field in the array is the field which is added to your field_collection_item
entity (Notice the bundle in the instance is same as your field_name on node: bir_collection. This is how the connection is made). In this particular example, it's a node_reference
type field, but this can be any other field type that's available to your Drupal instance.
The order has to be in this sequence, since you need to add the field_collection
type field to your node to create the field_collection_item
entity, then you add the fields to your field_collection_item
entity.