public function UniqueFieldValidationRule::validate in Field Validation 8
Overrides FieldValidationRuleBase::validate
File
- src/
Plugin/ FieldValidationRule/ UniqueFieldValidationRule.php, line 82
Class
- UniqueFieldValidationRule
- UniqueFieldValidationRule.
Namespace
Drupal\field_validation\Plugin\FieldValidationRuleCode
public function validate($params) {
$value = isset($params['value']) ? $params['value'] : '';
$rule = isset($params['rule']) ? $params['rule'] : null;
$context = isset($params['context']) ? $params['context'] : null;
$items = isset($params['items']) ? $params['items'] : array();
$delta = isset($params['delta']) ? $params['delta'] : '';
$column = $rule
->getColumn();
$settings = array();
if (!empty($rule) && !empty($rule->configuration)) {
$settings = $rule->configuration;
}
$flag = TRUE;
$scope = isset($settings['scope']) ? $settings['scope'] : '';
$per_user = $settings['per_user'] ?? FALSE;
$count = 0;
foreach ($items as $delta1 => $item1) {
if ($delta != $delta1) {
if ($value == $item1->{$column}) {
$flag = FALSE;
break;
}
}
}
if ($flag) {
$entity = $items
->getEntity();
$entity_type_id = $entity
->getEntityTypeId();
$query = \Drupal::entityQuery($entity_type_id);
$query
->addTag('field_validation');
$query
->accessCheck(FALSE);
if ($scope == 'bundle') {
$bundle = $entity
->bundle();
$bundle_key = $entity
->getEntityType()
->getKey('bundle');
/*
$bundle_keys = [
"node" => "type",
"taxonomy_term" => "vid",
"comment" => "comment_type",
"block_content" => "type",
];
*/
if (!empty($bundle_key)) {
$query
->condition($bundle_key, $bundle);
}
}
if ($per_user) {
$query
->condition('uid', \Drupal::currentUser()
->id());
}
$id_key = $entity
->getEntityType()
->getKey('id');
$query
->condition($id_key, (int) $items
->getEntity()
->id(), '<>');
$field_name = $items
->getFieldDefinition()
->getName();
if (!empty($column)) {
$field_name = $field_name . '.' . $column;
}
$query
->condition($field_name, $value);
$count = $query
->range(0, 1)
->count()
->execute();
if ($count) {
$flag = FALSE;
}
}
if (!$flag) {
$context
->addViolation($rule
->getErrorMessage());
}
//return true;
}