3 namespace Drupal\entity_browser\Plugin\EntityBrowser\WidgetValidation;
5 use Drupal\entity_browser\Element\EntityBrowserElement;
6 use Drupal\entity_browser\WidgetValidationBase;
7 use Symfony\Component\Validator\ConstraintViolation;
8 use Symfony\Component\Validator\ConstraintViolationList;
11 * Validates that the widget returns the appropriate number of elements.
13 * @EntityBrowserWidgetValidation(
15 * label = @Translation("Cardinality validator")
18 class Cardinality extends WidgetValidationBase {
23 public function validate(array $entities, $options = []) {
24 $violations = new ConstraintViolationList();
26 // As this validation happens at a level above the individual entities,
27 // we implement logic without using Constraint Plugins.
28 $count = count($entities);
29 $max = $options['cardinality'];
30 if ($max !== EntityBrowserElement::CARDINALITY_UNLIMITED && $count > $max) {
31 $message = $this->formatPlural($max, 'You can not select more than 1 entity.', 'You can not select more than @count entities.');
32 $violation = new ConstraintViolation($message, $message, [], $count, '', $count);
33 $violations->add($violation);