2

I have created a module which implements a CCK field. When adding the field to a content type, I have set the number of values to unlimited, and set the field to be required.

Is there a way to set the number of values required? I need the user to enter 5 or more values.

Thank you in advance.

MW.
  • 12,550
  • 9
  • 36
  • 65

1 Answers1

1

The answer lies within hook_form_alter() -- http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_form_alter/6

You'll need to do 2 things, as I see it:

  1. Alter the form item to include 5 entries on form load (instead of the usual 2 with an "add more" button).

  2. Add a $form['#validate'] = 'my_form_validate' entry to the form to check that at least 5 were set.

1 may be a bit of a challenge; I'm not sure how the form loads multiple items the first time around. If you do a vardump on the $form it may be obvious, though.

For 2 it should be straightforward --

function my_form_validate($form, &$form_state) {
  $i=0;
  foreach ($form_state['field_my_field_name']...) {
    if (isset(...)) { $i++; }
  }
  if ($i < 5) {
    form_set_error($form_state['field_my_field_name'], 'You must enter 5 foobars');
  }
}
Charlie Schliesser
  • 7,851
  • 4
  • 46
  • 76
  • 1
    Haven't figured out the first point yet, but the second worked like a charm. Although it's not as usable without displaying five elements to begin with, it's passable for now. Thanks! – MW. Jun 23 '11 at 07:50