Editing a Field Collection element in a custom module In a custom module, I'd like to to edit a Field Collection element. The element is linked to a taxonomy but I think the code would look quite similar if it was to a content type.

I've read a lot of documentation, source code, forum entries and Drupal articles, but I'm stuck.

In my hook_form() implementation, I've got:

$field_collection_item = entity_create('field_collection_item', array('field_name' =&gt; 'my_fc_field_name'));
// In a content type, use ('node', $node) instead
$field_collection_item-&gt;setHostEntity('taxonomy_term', $term);

// Not sure if those three lines are usefull
$field_node_example_values = field_get_items('taxonomy_term', $term, 'my_fc_field_name');
$field_node_example_ids = field_collection_field_item_to_ids($field_node_example_values);
$field_node_example_fc_items = field_collection_item_load_multiple($field_node_example_ids);

// Not sure if this line is correct
$form_state['field']['my_fc_field_name'] = $field_node_example_fc_items;


/* All examples below produce the same result : only one instance of the FC form appears, with no existing values and no buttons */

module_load_include('inc', 'field_collection', 'field_collection.pages');

// 1/
$form = field_collection_item_form($form, $form_state, $field_collection_item);

// OR

// 2/
$form['my_form_entry'] = array();
field_attach_form('field_collection_item', $field_collection_item, $form['my_form_entry'], $form_state);

// OR

// 3/
$output = drupal_get_form('field_collection_item_form', $field_collection_item);
$form['my_form_entry'] = $output;


So, my goal would be to get the same result as "out of the box" FC edit form, a nice fieldset with as many instances as exist, with Remove and Add buttons.

To be clear, I can see this type of form when I edit the taxonomy term, but I'd like to do it in a custom module.

I've look into the FC module, specifically the field_collection_field_attach_form and field_collection_field_widget_form functions, but I'm not sure how I could use them.

Some useful articles and forum entries:


http://www.cocomore.com/blog/field-collections-exposed
https://www.drupal.org/node/1842304
How to pre-populate multiple &quot;field collection&quot; fields in node form
https://stackoverflow.com/questions/13364905/need-an-example-on-attaching-a-field-collection-to-a-drupal-form-drupal-7
https://stackoverflow.com/questions/18447025/adding-drupal-field-collection-element-to-a-custom-form
https://www.drupal.org/node/1337804#comment-6326678
Strictly speaking on how to edit a field collection entity, once you have the field collection ID (you would get it from a field on your host entity, for example), you can load the collection using entity_metadata_wrapper, change it and them save it back.


$collection = entity_metadata_wrapper('field_collection_item', $collection_id);
// Do your change
// ...
$collection->save();