You are here

public function Cardinality::validate in Entity Browser 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/EntityBrowser/WidgetValidation/Cardinality.php \Drupal\entity_browser\Plugin\EntityBrowser\WidgetValidation\Cardinality::validate()

Validates the widget.

Parameters

array $entities: Array of selected entities.

array $options: (Optional) Array of options needed by the constraint validator.

Return value

\Symfony\Component\Validator\ConstraintViolationListInterface A list of constraint violations. If the list is empty, validation succeeded.

Overrides WidgetValidationBase::validate

File

src/Plugin/EntityBrowser/WidgetValidation/Cardinality.php, line 23

Class

Cardinality
Validates that the widget returns the appropriate number of elements.

Namespace

Drupal\entity_browser\Plugin\EntityBrowser\WidgetValidation

Code

public function validate(array $entities, array $options = []) {
  $violations = new ConstraintViolationList();

  // As this validation happens at a level above the individual entities,
  // we implement logic without using Constraint Plugins.
  $count = count($entities);
  $max = $options['cardinality'];
  if ($max !== EntityBrowserElement::CARDINALITY_UNLIMITED && $count > $max) {
    $message = $this
      ->formatPlural($max, 'You can only select one item.', 'You can only select up to @number items.', [
      '@number' => $max,
    ]);
    $violation = new ConstraintViolation($message, $message, [], $count, '', $count);
    $violations
      ->add($violation);
  }
  return $violations;
}