Question

I'd like to add a Field Collection Item to my custom form. My form is a custom event registration (will save data to Event Registration node), and the field collection is available in Event Registration Content type. I tried many codes and tries but none of them works.

module_load_include('inc', 'field_collection', 'field_collection.pages');
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_participant'));
$entity_form = field_collection_item_form($form, $form_state, $field_collection_item);
$form['participant'] = $entity_form;

This loads the field collection item to my form, but I can't add another Field collection item and the form other elements (company, phone, etc.) is duplicated. I found another line that maybe should be add:

$field_collection_item->setHostEntity('node', $node);

but in that moment I haven't $node and I'm not sure it has to be.

Was it helpful?

Solution

I see the issue that you are having. You are building the field collection form, and then you are trying to build an additional field collection form, but the content is not being attached.

I think that instead, you want to use the following

module_load_include('inc', 'field_collection', 'field_collection.pages');
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_collection_name'));
field_attach_form('field_collection_item', $field_collection_item, $form['participant'], $form_state);

That will allow you to attach numerous field collection items by changing the location in field_attach_form

module_load_include('inc', 'field_collection', 'field_collection.pages');
for ($i=0;$i<5;$i++) {
  $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_collection_name'));
  $form['category'][$i] = array();
  field_attach_form('field_collection_item', $field_collection_item, $form['category'][$i], $form_state);
}

Make sure to set the #parent attribute on your original $form, otherwise your data will be joined together on submit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top