You are here

public function FieldStorageConfigEditForm::validateCardinality in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/field_ui/src/Form/FieldStorageConfigEditForm.php \Drupal\field_ui\Form\FieldStorageConfigEditForm::validateCardinality()
  2. 9 core/modules/field_ui/src/Form/FieldStorageConfigEditForm.php \Drupal\field_ui\Form\FieldStorageConfigEditForm::validateCardinality()

Validates the cardinality.

Parameters

array $element: The cardinality form render array.

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

File

core/modules/field_ui/src/Form/FieldStorageConfigEditForm.php, line 186

Class

FieldStorageConfigEditForm
Provides a form for the "field storage" edit page.

Namespace

Drupal\field_ui\Form

Code

public function validateCardinality(array &$element, FormStateInterface $form_state) {
  $field_storage_definitions = \Drupal::service('entity_field.manager')
    ->getFieldStorageDefinitions($this->entity
    ->getTargetEntityTypeId());

  // Validate field cardinality.
  if ($form_state
    ->getValue('cardinality') === 'number' && !$form_state
    ->getValue('cardinality_number')) {
    $form_state
      ->setError($element['cardinality_number'], $this
      ->t('Number of values is required.'));
  }
  elseif (!$this->entity
    ->isNew() && isset($field_storage_definitions[$this->entity
    ->getName()]) && $form_state
    ->getValue('cardinality') != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {

    // Get a count of entities that have a value in a delta higher than the
    // one selected. Deltas start with 0, so the selected value does not
    // need to be incremented.
    $entities_with_higher_delta = \Drupal::entityQuery($this->entity
      ->getTargetEntityTypeId())
      ->accessCheck(FALSE)
      ->condition($this->entity
      ->getName() . '.%delta', $form_state
      ->getValue('cardinality'))
      ->count()
      ->execute();
    if ($entities_with_higher_delta) {
      $form_state
        ->setError($element['cardinality_number'], $this
        ->formatPlural($entities_with_higher_delta, 'There is @count entity with @delta or more values in this field.', 'There are @count entities with @delta or more values in this field.', [
        '@delta' => $form_state
          ->getValue('cardinality') + 1,
      ]));
    }
  }
}