UniqueFieldValueValidator.php in Drupal 9
File
core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/UniqueFieldValueValidator.php
View source
<?php
namespace Drupal\Core\Validation\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class UniqueFieldValueValidator extends ConstraintValidator {
public function validate($items, Constraint $constraint) {
if (!($item = $items
->first())) {
return;
}
$field_name = $items
->getFieldDefinition()
->getName();
$entity = $items
->getEntity();
$entity_type_id = $entity
->getEntityTypeId();
$id_key = $entity
->getEntityType()
->getKey('id');
$query = \Drupal::entityQuery($entity_type_id);
$query
->accessCheck(TRUE);
$entity_id = $entity
->id();
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()),
]);
}
}
}