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