You are here

UniqueFieldConstraintValidator.php in Unique field 8

File

src/Plugin/Validation/Constraint/UniqueFieldConstraintValidator.php
View source
<?php

/**
 * @file
 * Contains \Drupal\unique_field\Plugin\Validation\Constraint\UniqueFieldConstraintValidator.
 */
namespace Drupal\unique_field\Plugin\Validation\Constraint;

use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Drupal\Component\Utility\Unicode;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the UniqueField constraint.
 */
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;
    }
  }

}

Classes

Namesort descending Description
UniqueFieldConstraintValidator Validates the UniqueField constraint.