You are here

public function LayoutParagraphsWidget::newItemValidate in Layout Paragraphs 1.0.x

New item validator - checks cardinality.

Parameters

array $element: The element to validate.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

File

src/Plugin/Field/FieldWidget/LayoutParagraphsWidget.php, line 1463

Class

LayoutParagraphsWidget
Entity Reference with Layout field widget.

Namespace

Drupal\layout_paragraphs\Plugin\Field\FieldWidget

Code

public function newItemValidate(array $element, FormStateInterface $form_state) {
  $triggering_element = $form_state
    ->getTriggeringElement();

  // Only check cardinality if the user clicked to add a new paragraph.
  if ($triggering_element['#array_parents'] == $element['#array_parents']) {
    $parents = $element['#element_parents'];
    $widget_state = static::getWidgetState($parents, $this->fieldName, $form_state);
    $count = $this
      ->activeItemsCount($widget_state['items']);
    $cardinality = $this->fieldDefinition
      ->getFieldStorageDefinition()
      ->getCardinality();
    if ($cardinality != -1 && $count >= $cardinality) {
      $form_state
        ->setError($element, $this
        ->t('You can only add @cardinality or fewer items.', [
        '@cardinality' => $cardinality,
      ]));
    }
  }
}