Is there a way to modify the behavior of a field that has limited input to do the 'add more items' button instead of show X fields on the screen?

For instance, I have added a link field, that can have up to 5 link values. When it is displayed on the form, it shows 5 empty link fields, instead of one with the option to add more. This display is cumbersome, and makes users believe they must fill all of the fields in, and conversely, become unsure how to 'remove' a link since clearing the field value is less intuitive than clicking 'Remove' that some other fields have.

For UX/training purposes, I would like for fields on forms to behave consistently for limited or unlimited. Has anyone accomplished this behavior using the Form API?

  • Is this a Form API specific question? – Stefanos Petrakis Dec 13 '16 at 8:31
  • My advice would be to configure it as unlimited cardinality (value -1) and use jQuery to disable the "Add another item" button after 4 clicks. I'm no jQuery hero though so maybe you can update your question with this specific information and ask for some jQuery help. – Wim Mostrey Jan 9 '17 at 22:21
  • I have a similar problem and think drupal.org/project/limited_field_widgets addresses it. – foonambolo Apr 12 '19 at 15:33

You can do this in a form alter:

     YOURMODULE_form_alter(&$form, &$form_state, $form_id) {

        if ($form_id == 'YOURFORM') {
           if (isset($form['YOURFILED']['und']['#max_delta']) && $form['YOURFIELD']['und']['#max_delta'] == 4) {
                $form['YOURFIELD']['und']['add_more']['#prefix'] = '<div style="display:none;">';
                $form['YOURFIELD']['und']['add_more']['#suffix'] = '</div>';

The max delta should be one less than you want as the maximum. When the delta is 4, then after five addmore fields, the add more button will be hidden.

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.