I'm trying to create entities from my custom form. To do that, I created "Add more" button, where I'm dynamically adding new elements that I'm attaching fields to by using:

field_attach_form('myentity', $entity, $form['wrapper']['myentities'][$key]['fields'], $form_state);

I would like to create entities in submit callback with field values from those elements.

The problem is, that when I have a multiple elements, inputs for the same type of fields of different entities have the same "name" attribute (eg. field_myfield[und][0][value]), which means that I can access only the value from the field of the last entity in the submit callback, which means that I cannot fill my entity with proper values before saving. I tried to put '#tree' => TRUE up the form tree, and unset this value on field level, but it didn't change an input name, and "values" structure.

How can I have in my submit callback access to all of the field values, so I could use them for creating entities?

  • $form['wrapper']['myentities'][$key]['fields'] what is the $key variable here? Could you post a bit more context of what your form looks like? Normally setting the form['#tree'] to true should do the trick. – Suranga Panagamuwa Gamage May 18 '15 at 23:25
  • $key is a number, in submit handler I'm creating basic entity objects and adding them to array in $form_state $form_state['myentities'][] = entity_create(...), and during ajax replacing, in my main form building function I'm iterating over this array and creating form elements for those entities with attaching fields. – Łukasz Zaroda May 19 '15 at 7:54
  • Apperantly you have to use the #parents key to fix this, see the documentation on field_attach_form. – Suranga Panagamuwa Gamage May 19 '15 at 12:12

You need to use the #parents variable as documented in the field_attach_form page. See field_attach_form

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.