By default the Field API in Drupal 7 displays an extra empty field in a field with multiple values when editing the form.  There is no setting for suppressing this display at in the Drupal backend and so it has to be done with some scripts.  The following example is for a custom field made using hook_field_widget_info() and is implemented in the widget form function.  Here is a screenshot of the custom field with the extra field displayed:

Extra empty field

Having that extra field is not always desirable.  In this case there is validation on the field to ensure that at least one of the answers is checked as correct.  Suppressing that display is not always easy.  There are some help articles that suggest using #max_delta, but that is there for a different purpose and Drupal keeps count of the number of fields displayed in a variable in $form_state.  After much research, following is the method I found.

First we need to ensure that we are targeting the form when the page is freshly loaded and the input array is empty (ie no ajax call has been made to add another item). We also have to make sure that we are on the last item and that it is an empty one.  Then we have to do two things:

  1.  Downward increment the field item count
  2.  Return false on the field item so that it is not rendered

 * Implements hook_field_widget_form().
function MYMODULE_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  // Don't render empty field at start
  $num_items = count($items);
  if (empty($form_state['input'])) {
    if ($delta > 0 && $num_items < $delta + 1) {
      return FALSE;

It should be possible to apply similar logic using hook_field_widget_form_alter this time getting the language code and actual number of items from the $form_state array.


User login