class UniqueFieldValueValidator

Same name in other branches
  1. 9 core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/UniqueFieldValueValidator.php \Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldValueValidator
  2. 10 core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/UniqueFieldValueValidator.php \Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldValueValidator
  3. 11.x core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/UniqueFieldValueValidator.php \Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldValueValidator

Validates that a field is unique for the given entity type.

Hierarchy

  • class \Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldValueValidator extends \Symfony\Component\Validator\ConstraintValidator

Expanded class hierarchy of UniqueFieldValueValidator

File

core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/UniqueFieldValueValidator.php, line 11

Namespace

Drupal\Core\Validation\Plugin\Validation\Constraint
View source
class UniqueFieldValueValidator extends ConstraintValidator {
    
    /**
     * {@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');
        $query = \Drupal::entityQuery($entity_type_id);
        $entity_id = $entity->id();
        // Using isset() instead of !empty() as 0 and '0' are valid ID values for
        // entity types using string IDs.
        if (isset($entity_id)) {
            $query->condition($id_key, $entity_id, '<>');
        }
        $value_taken = (bool) $query->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()
                    ->getSingularLabel(),
                '@field_name' => mb_strtolower($items->getFieldDefinition()
                    ->getLabel()),
            ]);
        }
    }

}

Members

Title Sort descending Modifiers Object type Summary
UniqueFieldValueValidator::validate public function

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.