You are here

class UniqueFieldConstraintValidator in Unique field 8

Validates the UniqueField constraint.

Hierarchy

Expanded class hierarchy of UniqueFieldConstraintValidator

File

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

Namespace

Drupal\unique_field\Plugin\Validation\Constraint
View source
class UniqueFieldConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  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']));
    }
  }
  public function BuildQuery($field_name, $field_value, $bundle = NULL, $scope = NULL) {
    if (!empty($scope)) {
      $query = \Drupal::entityQuery('node');
      switch ($scope) {
        case 'all':
          $query
            ->condition($field_name, $field_value, '=');
          break;
        case 'type':
          $query
            ->condition($field_name, $field_value, '=');
          $query
            ->condition('type', $bundle, '=');
          break;
      }
      $nids = $query
        ->execute();
      return $nids;
    }
  }

}

Members