Problem/Motivation
Property constraints validation adding errors to the field element instead of just the property.
Steps to reproduce
Create a custom module including:
function custom_module_entity_bundle_field_info_alter($fields, EntityTypeInterface $entity_type) {
if ($entity_type->id() == 'media'&& !empty($fields['field_media_image'])) {
/** @var \Drupal\field\Entity\FieldConfig[] $fields */
$fields['field_media_image']->addPropertyConstraints('alt', ['AltTextContainsLlamas' => []]);
}
}
Create the AltTextContainsLlamas constraint with:
public function validate(mixed $value, Constraint $constraint): void {
if (is_string($value) && !str_contains(strtolower($value), 'llamas')) {
$this->context->buildViolation($constraint->message)
->setInvalidValue($value)
->addViolation();
}
}
Enable the module. Enable media core module.
Edit Image media type to ensure you have alt and title.
Go to Add media. Upload an image.
Expected result:
Alt is marked as errored. Title is not.
Actual result:
Both alt and title are marked as errors.
If you enable Inline Form Errors you can see that even the file itself is marked as errored.
See screenshot
Proposed resolution
Implement errorElement in image widget.
Remaining tasks
Fix.