UniqueFieldValueValidator.php in Zircon Profile 8
Same filename and directory in other branches
File
core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/UniqueFieldValueValidator.phpView source
<?php
/**
* @file
* Contains \Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldValueValidator.
*/
namespace Drupal\Core\Validation\Plugin\Validation\Constraint;
use Drupal\Component\Utility\Unicode;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates that a field is unique for the given entity type.
*/
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');
$value_taken = (bool) \Drupal::entityQuery($entity_type_id)
->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' => Unicode::strtolower($items
->getFieldDefinition()
->getLabel()),
]);
}
}
}
Classes
Name | Description |
---|---|
UniqueFieldValueValidator | Validates that a field is unique for the given entity type. |