You are here

class FieldListUniqueValuesValidator in Helper 8

Validates duplicate field values.

Hierarchy

Expanded class hierarchy of FieldListUniqueValuesValidator

File

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

Namespace

Drupal\helper\Plugin\Validation\Constraint
View source
class FieldListUniqueValuesValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($value, Constraint $constraint) {

    /** @var \Drupal\Core\Field\FieldItemListInterface $value */

    /** @var \Drupal\helper\Plugin\Validation\Constraint\FieldListUniqueValues $constraint */

    // If the field is empty or doesn't have more than one value, there is
    // nothing to validate.
    if (!isset($value) || count($value) <= 1) {
      return;
    }
    if ($duplicates = Field::getDuplicateValues($value, $constraint->property)) {
      if ($constraint->show_values) {
        $this->context
          ->addViolation($constraint->messageWithValues, [
          '%field_name' => $value
            ->getFieldDefinition()
            ->getLabel(),
          '@values' => implode(', ', $duplicates),
        ]);
      }
      else {
        $this->context
          ->addViolation($constraint->message, [
          '%field_name' => $value
            ->getFieldDefinition()
            ->getLabel(),
        ]);
      }
    }
  }

}

Members

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