3 namespace Drupal\Core\Validation\Plugin\Validation\Constraint;
5 use Drupal\Component\Utility\Unicode;
6 use Symfony\Component\Validator\Constraint;
7 use Symfony\Component\Validator\ConstraintValidator;
10 * Validates that a field is unique for the given entity type.
12 class UniqueFieldValueValidator extends ConstraintValidator {
17 public function validate($items, Constraint $constraint) {
18 if (!$item = $items->first()) {
21 $field_name = $items->getFieldDefinition()->getName();
22 /** @var \Drupal\Core\Entity\EntityInterface $entity */
23 $entity = $items->getEntity();
24 $entity_type_id = $entity->getEntityTypeId();
25 $id_key = $entity->getEntityType()->getKey('id');
27 $value_taken = (bool) \Drupal::entityQuery($entity_type_id)
28 // The id could be NULL, so we cast it to 0 in that case.
29 ->condition($id_key, (int) $items->getEntity()->id(), '<>')
30 ->condition($field_name, $item->value)
36 $this->context->addViolation($constraint->message, [
37 '%value' => $item->value,
38 '@entity_type' => $entity->getEntityType()->getLowercaseLabel(),
39 '@field_name' => Unicode::strtolower($items->getFieldDefinition()->getLabel()),