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

Created on 25 February 2025, 2 months ago

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.

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

Merge Requests

Comments & Activities

Production build 0.71.5 2024