class UniqueFieldValueValidator in Zircon Profile 8
Same name and namespace in other branches
- 8.0 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 \Symfony\Component\Validator\ConstraintValidator implements ConstraintValidatorInterface
- class \Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldValueValidator
Expanded class hierarchy of UniqueFieldValueValidator
File
- core/
lib/ Drupal/ Core/ Validation/ Plugin/ Validation/ Constraint/ UniqueFieldValueValidator.php, line 17 - Contains \Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldValueValidator.
Namespace
Drupal\Core\Validation\Plugin\Validation\ConstraintView 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');
$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()),
]);
}
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
ConstraintValidator:: |
protected | property | 3 | |
ConstraintValidator:: |
protected | function | Wrapper for {@link ExecutionContextInterface::buildViolation} that supports the 2.4 context API. | |
ConstraintValidator:: |
protected | function | Wrapper for {@link ExecutionContextInterface::buildViolation} that supports the 2.4 context API. | |
ConstraintValidator:: |
protected | function | Returns a string representation of the type of the value. | |
ConstraintValidator:: |
protected | function | Returns a string representation of the value. | |
ConstraintValidator:: |
protected | function | Returns a string representation of a list of values. | |
ConstraintValidator:: |
public | function |
Initializes the constraint validator. Overrides ConstraintValidatorInterface:: |
1 |
ConstraintValidator:: |
constant | Whether to cast objects with a "__toString()" method to strings. | ||
ConstraintValidator:: |
constant | Whether to format {@link \DateTime} objects as RFC-3339 dates ("Y-m-d H:i:s"). | ||
UniqueFieldValueValidator:: |
public | function |
Checks if the passed value is valid. Overrides ConstraintValidatorInterface:: |