Unlimited cardinality pre-populate fields

I am trying to solve this and my only issue is that I want to keep this field as unlimited cardinality with fields in Field Collection already displayed to the user when they create the other reference node.

function module_form_alter(&$form, &$form_state, $form_id) {
     if($form_id == 'form_name') {
         $reference_query = new EntityFieldQuery();
         $reference_query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'reference')
          ->propertyOrderBy('created', 'DESC')
          ->range(0, 1);
        $reference_result = $reference_query->execute();
        $reference_nid = array_keys($reference_result['node']);
        $reference_refer = node_load($reference_nid);
 
        $items_count = count($reference_refer->field_field_name['und']);
        $field_name = 'field_field_name';
        $form_theme = $form[$field_name]['und']['#theme'];
        // Remove delete and add more buttons
        $form[$field_name]['und'][0]['remove_button']['#access'] = FALSE;
        $form[$field_name]['und']['add_more']['#access'] = FALSE;
        $items = &$form_state['field'][$field_name]['und'];
 
        if ($items_count > 1 and $items['items_count'] != $items_count) {
          $items['items_count'] = $items_count;
          $items['field']['cardinality'] = $items_count;
          $form[$field_name]['und'] = field_multiple_value_form($items['field'], $items['instance'], LANGUAGE_NONE, array(), $form, $form_state);
            // Reset theme function
            $form[$field_name]['und']['#theme'] = $form_theme;
        }
 
        for ($delta = 0; $delta < $items_count; $delta++) {
           $form[$field_name]['und'][$delta]['value']['#default_value'] = $reference_refer->field_field_name['und'][$delta]['value'];
        }
    }
}

Tags:

Posted in Drupal