Issue #2894634 by amateescu: Allow entity-level validations to flag errors on form elements

8.4.x
Lee Rowlands 2017-07-15 18:09:13 +10:00
parent 2db1774546
commit 5ea0e3ae8d
No known key found for this signature in database
GPG Key ID: 2B829A3DF9204DC4
4 changed files with 15 additions and 1 deletions

View File

@ -235,7 +235,7 @@ class ContentEntityForm extends EntityForm implements ContentEntityFormInterface
// Flag entity level violations.
foreach ($violations->getEntityViolations() as $violation) {
/** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */
$form_state->setErrorByName('', $violation->getMessage());
$form_state->setErrorByName(str_replace('.', '][', $violation->getPropertyPath()), $violation->getMessage());
}
// Let the form display flag violations of its fields.
$this->getFormDisplay($form_state)->flagWidgetsErrorsFromViolations($violations, $form, $form_state);

View File

@ -68,6 +68,11 @@ class EntityConstraintViolationList extends ConstraintViolationList implements E
if ($this->entity->hasField($field_name)) {
$this->violationOffsetsByField[$field_name][$offset] = $offset;
}
// If the first part of the violation property path is not a valid
// field name, we're dealing with an entity-level validation.
else {
$this->entityViolationOffsets[$offset] = $offset;
}
}
else {
$this->entityViolationOffsets[$offset] = $offset;

View File

@ -25,6 +25,11 @@ class EntityTestEntityLevelValidator extends ConstraintValidator {
$this->context->buildViolation($constraint->message)
->addViolation();
}
if ($value->name->value === 'entity-level-violation-with-path') {
$this->context->buildViolation($constraint->message)
->atPath('test.form.element')
->addViolation();
}
}
}

View File

@ -149,6 +149,10 @@ class FieldWidgetConstraintValidatorTest extends KernelTestBase {
$errors = $this->getErrorsForEntity($entity);
$this->assertEqual($errors[''], 'Entity level validation');
$entity->name->value = 'entity-level-violation-with-path';
$errors = $this->getErrorsForEntity($entity);
$this->assertEqual($errors['test][form][element'], 'Entity level validation');
}
}