0

How can I (either with a module or programmatically) limit the number of values for multiple fields? For example, the user can add only a single value for field A OR field B OR field C. The total maximum number of values behind all fields can't exceed 1.

  • 1
    So if user fills in B, they cannot longer enter a value for A and C? – No Sssweat Nov 27 '19 at 6:45
  • Yes, Only one value total. – Sam Nov 28 '19 at 1:54
1

Using a contrib module: You can use the conditional_fields module.

Doing it programatically: You can use the #states property in a custom form or form_alter hook.

You must add this to field A, B and C:

'#states' => [
  'invisible' => [
    [':input[name="field-name"]' => ['filled' => TRUE]],
    'or',
    [':input[name="field-name-2"]' => ['filled => TRUE]],
  ],
],

Of course you have to replace "field-name" and "field-name-2" with the two field names that are not the one adding the states to, hope it makes sense.

If you can’t find the name of the field you can look in the browser inspector to get the name of the input field.

  • Does conditional fields work on forms or just front-end? – Sam Nov 28 '19 at 2:10
  • 1
    It works for entity forms(node form, user form etc.). So it will automatically work in the front-end too since it will only allow you to input one field value if configured correctly. – user72672 Nov 28 '19 at 5:50

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.