Drupal - Unlimited values field - how to hide extra field on node edit

This would work for all node edit forms:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  $field_name = 'field_YOURFIELD';

  if (empty($form[$field_name])) {
    return;
  }

  $field_language = $form[$field_name]['#language'];
  $max_delta = $form[$field_name][$field_language]['#max_delta'];
  unset($form[$field_name][$field_language][$max_delta]);
}

This would work for all node edit forms without even specifying the field names.

/**
 * Implements hook_form_NODE_FORM_alter().
 */
function MY_MODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['#node']->nid) && $form['#node']->nid > 0) {
    $form_fields = array_keys($form);

    foreach ($form_fields as $index => $field_name) {
      if (substr($field_name, 0, 6) == "field_") { // Check if the field is a custom field
        $field_language = $form[$field_name]['#language'];
        if (isset($form[$field_name][$field_language]['#cardinality']) && 
            $form[$field_name][$form[$field_name]['#language']]['#cardinality'] == -1) {

          if (empty($form[$field_name])) {
            continue;
          }

          $max_delta = $form[$field_name][$field_language]['#max_delta'];
          unset($form[$field_name][$field_language][$max_delta]);

        }
      }
    }

  }
}

You could write your own module with a hook_form_FORM_ID_alter to remove the unwanted field. Something like...

function my_module_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  // Do checks here to make sure this is an existing node...

  // Get the index of the last input element in this field
  $last_index = $form['field_field_name'][LANGUAGE_NONE]['#max_delta'];
  // Get rid of the last input element
  unset($form['field_field_name'][LANGUAGE_NONE][$last_index]);
  // Move back the last index so that any new elements are added correctly
  $form['field_field_name'][LANGUAGE_NONE]['#max_delta'] = $last_index-1;
}

Tags:

Entities

7