6

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
3

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.

| improve this answer | |
0

In Drupal 8 the above solution does not work. How I achieved this by setting the field configuration from a limit to "unlimited" (cardinality: -1) and with a customs module form alter to manage the field limit

Example: In your example.module

use Drupal\Core\Form\FormStateInterface;

/**
 * @param array $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function example_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $limit = 100;

  if ($form_id === 'node_xyz_edit_form') {
    if (isset($form['field_abc']['widget']['#max_delta']) && $form['field_abc']['widget']['#max_delta'] >= $limit) {
      unset($form['field_abc']['widget']['add_more']);
    }
  }
}

Where 'example' will be your module name, 'node_xyz_edit_form' will be your node form id and 'field_abc' will be the content-type field.

| improve this answer | |

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.