You are here

public function UniqueFieldConstraintValidator::validate in Unique field 8

File

src/Plugin/Validation/Constraint/UniqueFieldConstraintValidator.php, line 24
Contains \Drupal\unique_field\Plugin\Validation\Constraint\UniqueFieldConstraintValidator.

Class

UniqueFieldConstraintValidator
Validates the UniqueField constraint.

Namespace

Drupal\unique_field\Plugin\Validation\Constraint

Code

public function validate($items, Constraint $constraint) {
  if (!isset($items)) {
    return;
  }
  $field['type'] = !empty($items
    ->getFieldDefinition()->field_type) ? $items
    ->getFieldDefinition()->field_type : '';
  $field['name'] = $items
    ->getName();
  $field['raw_value'] = $items
    ->getvalue();
  $field['label'] = $items
    ->getFieldDefinition()
    ->getLabel();
  if (!empty($field['type']) && $field['type'] == 'taxonomy_term_reference') {
    $field['value'] = $field['raw_value']['0']['target_id'];
    $selected_value = $items->entity
      ->getName();
  }
  else {
    $field['value'] = $field['raw_value']['0']['value'];
    $selected_value = $field['value'];
  }
  $nids = $this
    ->BuildQuery($field['name'], $field['value'], $constraint->bundle, $constraint->scope);
  $nid = \Drupal::routeMatch()
    ->getParameter('node')
    ->id();

  //unset current node ID.
  unset($nids[$nid]);
  foreach ($nids as $value) {
    $node = Node::load($value);

    //$url = Url::fromUri($node->url());
    $title = $node
      ->getTitle();
    $url_list[] = \Drupal::l($node
      ->getTitle(), $node
      ->urlInfo());
  }
  if (!empty($nids) && sizeof($nids) > 0) {
    drupal_set_message(t($constraint->matches, array(
      '!node' => $url_list['0'],
    )));
    $this->context
      ->addViolation($constraint->UniqueMessage, array(
      '%label' => $field['label'],
      '%value' => $selected_value,
    ));

    //$this->context->addViolation($constraint->matches, array('!node' => $url_list['0']));
  }
}