You are here

class MachineNameUniqueValidator in Machine name 8

Validates that a field is unique for the given entity type.

Hierarchy

  • class \Drupal\machine_name\Plugin\Validation\Constraint\MachineNameUniqueValidator extends \Symfony\Component\Validator\ConstraintValidator

Expanded class hierarchy of MachineNameUniqueValidator

File

src/Plugin/Validation/Constraint/MachineNameUniqueValidator.php, line 12

Namespace

Drupal\machine_name\Plugin\Validation\Constraint
View source
class MachineNameUniqueValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($item, Constraint $constraint) {
    if ($item
      ->isEmpty()) {
      return NULL;
    }
    $entity = $item
      ->getEntity();
    $entity_id = $entity
      ->id();
    $entity_type = $entity
      ->getEntityType();
    $field_name = $item
      ->getFieldDefinition()
      ->getName();
    $properties = $item
      ->getProperties();

    // Query to see if existing entity with machine name exists.
    $query = \Drupal::entityQuery($entity_type
      ->id());
    foreach ($properties as $property) {
      $query
        ->condition($field_name . '.value', $property
        ->getValue());
      if (!empty($entity_id)) {
        $query
          ->condition($entity_type
          ->getKey('id'), $entity_id, '<>');
      }
      $result = $query
        ->execute();
      if (!empty($result)) {
        $this->context
          ->addViolation($constraint->message, array(
          '%value' => $property
            ->getValue(),
        ));
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
MachineNameUniqueValidator::validate public function Checks if the passed value is valid.