Add unlimited field collections in a from of drupal I created a form in drupal for creating a new node. This content type has a field collection with 2 fields, name and amount.
I use the code below  in form and add 5 field collections to form, but when submit the form, only the last field collection is saved in $form_state['values] and 4 elements get lost.
How can I add unlimited field collections to a form by programming?

In my form:

module_load_include('inc', 'field_collection', 'field_collection.pages');
$form['cooking_type']['cooking_materials']  = array();
 for ($i=0;$i&lt;5;$i++) {
$field_collection_item = entity_create('field_collection_item', array('field_name' =&gt; 'field_cooking_materials'));
$form['cooking_type']['cooking_materials'][$i] = array();
field_attach_form('field_collection_item', $field_collection_item, $form['cooking_type']['cooking_materials'][$i], $form_state);
}


in submit form:

$material_name= $form_state['values']['field_material_name']['und'][0]['value'];
$material_amount = $form_state['values']['field_material_amount']['und'][0]['value'];
This is a working code that can be placed directly into your form function. Please see the comments too.

$node = new stdClass();
// Replace the value to the content type's machine name where you have added
// the field collection field
$node-&gt;type = 'CONTENT_TYPE';

// Prepare the field collection display array
$form['field_collection_display'] = array();

// Get the field collection field's info/structure and return it to the given variable
// w/c in our case is $form['field_collection_display']
field_attach_form('node', $node, $form['field_collection_display'], $form_state, NULL, array(
  'field_name' =&gt; 'FIELD_COLLECTION_FIELD_NAME'
));

$form['submit'] = array(
  '#type' =&gt; 'submit',
  '#value' =&gt; 'Submit',
);

return $form;


For the "Add another item" display, when you go the the field collection's content manage field settings page it says that the button will only display when it's set to 'Unlimited' w/c isn't your requirement. So you would need to add custom validations to this.

Since this is also custom coding, if you're having a hard time manipulating the field I would also recommend looking at doing the "field collection" functionality by yourself. This is the link https://api.drupal.org/api/examples/form_example!form_example.module/group/form_example/7. You could go to the form_example_tutorial_9 directly if you want.