Add the required amount of multiple fields into the form

Public

Code in hook_form_alter(&$form, &$form_state, $form_id).

</> CopyGet raw version
php
  1. $items_count = count($SOME_OBJECTS_ARRAY);
  2. $field_name = 'MY_FIELD_NAME';
  3. // Remove delete button
  4. $form[$field_name][LANGUAGE_NONE][0]['remove_button']['#access'] = FALSE;
  5. // Remove button add more
  6. $form[$field_name][LANGUAGE_NONE]['add_more']['#access'] = FALSE;
  7. $items = &$form_state['field'][$field_name][LANGUAGE_NONE];
  8. // Generate required number of fields collection
  9. if ($items_count > 1 and $items['items_count'] != $items_count) {
  10. $items['items_count'] = $items_count;
  11. $items['field']['cardinality'] = $items_count;
  12. $form[$field_name][LANGUAGE_NONE] = field_multiple_value_form($items['field'], $items['instance'], LANGUAGE_NONE, array(), $form, $form_state);
  13. }
  14. // Fill generated fields with data
  15. for ($delta = 0; $delta < $items_count; $delta++) {
  16. $form[$field_name][LANGUAGE_NONE][$delta]['some_field_1'][LANGUAGE_NONE]['#default_value'] = $current_order->commerce_line_items[LANGUAGE_NONE][$delta]['line_item_id'];
  17. $form[$field_name][LANGUAGE_NONE][$delta]['some_field_2'][LANGUAGE_NONE]['#title'] = 'Some title ' . $delta;
  18. }

Comments

tof's picture

Hi
I try your code, it works the field have been prepopulated, but when I save the node, an error appears :
EntityMalformedException : Missing bundle property on the type of entity field_collection_item in entity_extract_ids() (ligne 7766 in ../includes/common.inc).
Any ideas ?

tostinni's picture

Thanks for this snippet, it works almost perfectly for me.
I havent used the generate data part (lines 14-18) and I added a small change (lines 8-13) so the values are kept :

  1. if ($items_count > 1 and $items['items_count'] != $items_count) {
  2. $items['items_count'] = $items_count;
  3. $items['field']['cardinality'] = $items_count;
  4. $values = field_get_items('node', $form['#node'], $field_name);
  5. $form[$field_name][LANGUAGE_NONE] = field_multiple_value_form($items['field'], $items['instance'], LANGUAGE_NONE, $values, $form, $form_state);
  6. }