0

I need to set the minimum number of required values for several file fields in Drupal 7. I can only find options to make the field required or set a maximum number of allowed values. Is there any way to set the MINIMUM number of required values?

3

You can use the Field validation module, and set up a validation rule using "number of selections".
The Field validation module has many validation rules you can set for any of your fields. It works by defining a set of validation rules at first, then you can assign that set to a field.

To answer your question, the validation rule you need to use is the "number of selections". You can define a minimum and a maximum number of values required. Just leave blank the "Maximum number of selections" parameter and set "Minimum number of selections" to your needs.

2

I found the field validation option resulted in a lot of form submission failure messages, the best was trying to add another field when I had only one complained that I did not have btwn 3 and 5, but did not give me another field.

My solution using hook_form_alter(): Not the most elegant code now that I look at it...

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  /**
  * Make sure that there are at least 3 and at most 5 items
  */
  if ($form_id == 'content_type_container_node_form') {

    // Count how many items we have
    $item_count = 0;
    foreach ($form['field_name_items'][ LANGUAGE_NONE ] as $delta => $item) {
      if (is_integer($delta)) {
        $item_count++;
      }
    }

    // If it is a new node then make sure we start with 3 items
    if ($form['nid']['#value'] == NULL && $item_count < 3) {
      $item_template = $form['field_name_items'][ LANGUAGE_NONE ][0];

      // We are adding two items to the one we already have
      for ($i = 1; $i < 3; $i++) {
        $form['field_name_items'][ LANGUAGE_NONE ][ $i ] = $item_template;
        $form['field_name_items'][ LANGUAGE_NONE ][ $i ]['remove_button']['#delta'] = $i;
      }
    }

    // Re-Count how many items we have
    $item_count = 0;
    foreach ($form['field_name_items'][ LANGUAGE_NONE ] as $delta => $item) {
      if (is_integer($delta)) {
        $item_count++;
        // Remove the 'Remove' link for the first 3 items
        if ($item_count <= 3) {
          unset($form['field_name_items'][ LANGUAGE_NONE ][ $delta ]['remove_button']);
        }

      }
    }

    if ($item_count == 5) {
      // Remove add more link if there are 5 items
      unset($form['field_name_items'][ LANGUAGE_NONE ]['add_more']);
    }
  }
}

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.