0

I am trying to figure out how can I add multiple field collections to a node when a user starts filling out a node.

Here is how my nodes are basically set up:

Color Card Content Type:
 - id
 - name
 - colors_term_reference(multi select)

Style Content Type:
 - id
 - color_card_node_reference (select)
 - color_images_collection (unlimited field collection)
   - color_term (single select)
   - image

When a user starts filling out the node form, I want the field collections to get created and all the colors that were chosen in the color card get preselected.

So ideally if color has the following colors: red, blue, and green, when a user starts filling out my style node and chooses that color card the field collection would have red, blue, and green preselected and they would only need to upload the images.

Color Card:
- id: 1
- name: Cool Colors
- colors_term_reference:
  10 (red)
  17 (blue)
  38 (green)

Style:
- id: 1
- color_card_node_reference: 1
- color_image_collection:
  0:
    color_term: 10,
    image:
  1:
    color_term: 17,
    image:
  2:
    color_term: 38:
    image:
0

I ended up using the same approach as How to create (& pre-populate) multiple “field collection” fields on an ajax call.

Use hook_form_FORM_ID_alter() to the node you need the functionality at.

// Add ajax callback when a node reference is entered or changed.
$form['field_node_reference'][LANGUAGE_NONE][0]['target_id']['#ajax'] = array(
  'callback' => 'your_module_ajax_rebuild_form',
  'wrapper' => 'field-collection-values',
);

Create ajax callback.

/**
 * Ajax callback, rebuilds and returns the field_collection_colorizer 
 * element.
 */
function your_module_ajax_rebuild_form() {
  // Get Field collections and children.
  $field_collection_colorizer = &$form_state['field']['field_collection'][LANGUAGE_NONE];
  $field_childs = &$form_state['field']['field_collection'][LANGUAGE_NONE]['entity'];

  // Found that I had to set item and items count in order for this to work.
  $field_collection_colorizer['item_count'] = $options_count;
  $field_collection_colorizer['items_count'] = $options_count;

  // Create any new field collection instances if needed.
  for ($i = 0; $i < $field_collection_colorizer['item_count']; $i++) {
    if (!isset($field_collection_colorizer['entity'][$i])) {
      $field_collection_colorizer['entity'][$i] = entity_create('field_collection_item', array('field_name' => 'field_collection_colorizer'));
    }
  }

  // Reset the input to make sure cached version of the form insn't returned.
  $form_state['input'] = array();

  // Rebuild the form.
  $form = drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);

  // Return the field you want to replace.
  return $form['field_collection_colorizer'];
}

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.