Unique field constraint does not validated field values on delta greater than 0

Created on 13 September 2018, almost 6 years ago
Updated 13 September 2023, 10 months ago

Problem/Motivation

Closer look at validator

/**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    if (!$item = $items->first()) {
      return;
    }
    $field_name = $items->getFieldDefinition()->getName();
    /** @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $items->getEntity();
    $entity_type_id = $entity->getEntityTypeId();
    $id_key = $entity->getEntityType()->getKey('id');

    $value_taken = (bool) \Drupal::entityQuery($entity_type_id)
      // The id could be NULL, so we cast it to 0 in that case.
      ->condition($id_key, (int) $items->getEntity()->id(), '<>')
      ->condition($field_name, $item->value)
      ->range(0, 1)
      ->count()
      ->execute();

    if ($value_taken) {
      $this->context->addViolation($constraint->message, [
        '%value' => $item->value,
        '@entity_type' => $entity->getEntityType()->getLowercaseLabel(),
        '@field_name' => mb_strtolower($items->getFieldDefinition()->getLabel()),
      ]);
    }
  }

reviled that only first field item is check for duplicates.

Proposed resolution

Add test coverage and fix validator.

Remaining tasks

  1. Write test to confirm bug
  2. Write test/s to cover all field types that doesn't have a field specific "unique" constraints/validators (see related issues)
  3. Review
  4. Commit

User interface changes

None

API changes

None

Data model changes

None

πŸ› Bug report
Status

Closed: outdated

Version

11.0 πŸ”₯

Component
BaseΒ  β†’

Last updated 1 minute ago

Created by

πŸ‡³πŸ‡ΏNew Zealand RoSk0 Wellington

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

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024