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.

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

1 Answer 1

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.

2
  • Does conditional fields work on forms or just front-end?
    – Sam
    Commented Nov 28, 2019 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
    Commented Nov 28, 2019 at 5:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.