Property constraints validation adding errors to the field element instead of just the property

Created on 16 April 2025, 10 days ago

Problem/Motivation

Property constraints validation adding errors to the field element instead of just the property.
This was fixed for images in 🐛 Property constraints validation adding errors to the field element instead of just the property Active , but we understand this might affect other elements, at least files.

Steps to reproduce

For image, this was 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 which widgets?
Remove from ImageWidget if needed.
Check tests added at 🐛 Property constraints validation adding errors to the field element instead of just the property Active and create similar for other widgets.

Remaining tasks

Fix.

User interface changes

Introduced terminology

API changes

Data model changes

Release notes snippet

🐛 Bug report
Status

Active

Version

11.0 🔥

Component

field system

Created by

🇪🇸Spain penyaskito Seville 💃, Spain 🇪🇸, UTC+2 🇪🇺

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024