You are here

public function DefaultParagraphsWidget::settingsFormDefaultParagraphsValidate in Default Paragraphs 8

Custom validate handler to check the default paragraph types.

File

src/Plugin/Field/FieldWidget/DefaultParagraphsWidget.php, line 262

Class

DefaultParagraphsWidget
Plugin implementation of the 'entity_reference_revisions paragraphs' widget.

Namespace

Drupal\default_paragraphs\Plugin\Field\FieldWidget

Code

public function settingsFormDefaultParagraphsValidate($element, FormStateInterface $form_state) {
  if (isset($element['#value'])) {
    $cardinality = $this->fieldDefinition
      ->getFieldStorageDefinition()
      ->getCardinality();
    $field_label = $this->fieldDefinition
      ->getLabel();
    if ($cardinality !== -1) {
      $default_paragraph_count = 0;
      foreach ($element['#value'] as $key => $data) {
        if (!empty($data['value'])) {
          $default_paragraph_count++;
        }
      }
      if ($default_paragraph_count > $cardinality) {
        $form_state
          ->setErrorByName('default_paragraph_types', t('@field field allows you to select not more than @total paragraph types as default.', [
          '@field' => $field_label,
          '@total' => $cardinality,
        ]));
      }
    }
  }
}