0

I have a custom validation constraint plugin that prevents submission if an entity reference field has an odd number of values. The validation triggers upon submission just fine

 public function validate($items, Constraint $constraint) { $cardinality = $items->getFieldDefinition()->get('fieldStorage')->get('cardinality'); $count = $cardinality == 1 ? $items->getValue()[0]['value'] : $items->count(); if (is_string($constraint->divisibleBy)) { switch ($constraint->divisibleBy) { case 'odd': if ($count % 2 == 0) { $this->context->buildViolation($constraint->notDivisible) ->setParameter('%field_name', $items->getFieldDefinition()->label()) ->setParameter('%divisibleBy', $constraint->divisibleBy) ->addViolation(); } break; case 'even': if ($count % 2 != 0) { $this->context->buildViolation($constraint->notDivisible) ->setParameter('%field_name', $items->getFieldDefinition()->label()) ->setParameter('%divisibleBy', $constraint->divisibleBy) ->addViolation(); } break; } } 

and in my custom paragraph class

 public static function alterFieldInfo(array &$fields): void { if (isset($fields['field_nodes'])) { $fields['field_nodes']->addConstraint('items_count_divisible', ['divisible_by' => 'even']); } if (isset($fields['field_maximum_items'])) { $fields['field_maximum_items']->addConstraint('items_count_divisible', ['divisible_by' => 'even']); } } 

However there's one major problem. When clicking 'Add more' to one of my fields it triggers the validation and stops the 'Add more' button from adding another field.

The number of values needs to be even to succeed validation but the form does not let me add more than one value because one value is odd and fails the validation.

Is there a way to prevent the validation from occurring if it's an ajax call rebuilding the form and not an actual form submission?

1 Answer 1

1

I was able to resolve this by setting the #limit_validation_errors property on the button to an empty array

Like so:

public static function alterFormElement(array &$element, FormStateInterface $form_state, array $context): void { $element['subform']['field_nodes']['widget']['add_more']['#limit_validation_errors'] = []; } 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.