function FileWidget::validateMultipleCount

Same name in other branches
  1. 8.9.x core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php \Drupal\file\Plugin\Field\FieldWidget\FileWidget::validateMultipleCount()
  2. 10 core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php \Drupal\file\Plugin\Field\FieldWidget\FileWidget::validateMultipleCount()
  3. 11.x core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php \Drupal\file\Plugin\Field\FieldWidget\FileWidget::validateMultipleCount()

Validates the number of uploaded files.

This validator is used only when cardinality not set to 1 or unlimited.

File

core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php, line 346

Class

FileWidget
Plugin implementation of the 'file_generic' widget.

Namespace

Drupal\file\Plugin\Field\FieldWidget

Code

public static function validateMultipleCount($element, FormStateInterface $form_state, $form) {
    $values = NestedArray::getValue($form_state->getValues(), $element['#parents']);
    $array_parents = $element['#array_parents'];
    array_pop($array_parents);
    $previously_uploaded_count = count(Element::children(NestedArray::getValue($form, $array_parents))) - 1;
    $field_storage_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions($element['#entity_type']);
    $field_storage = $field_storage_definitions[$element['#field_name']];
    $newly_uploaded_count = count($values['fids']);
    $total_uploaded_count = $newly_uploaded_count + $previously_uploaded_count;
    if ($total_uploaded_count > $field_storage->getCardinality()) {
        $keep = $newly_uploaded_count - $total_uploaded_count + $field_storage->getCardinality();
        $removed_files = array_slice($values['fids'], $keep);
        $removed_names = [];
        foreach ($removed_files as $fid) {
            $file = File::load($fid);
            $removed_names[] = $file->getFilename();
        }
        $args = [
            '%field' => $field_storage->getName(),
            '@max' => $field_storage->getCardinality(),
            '@count' => $total_uploaded_count,
            '%list' => implode(', ', $removed_names),
        ];
        $message = new TranslatableMarkup('Field %field can only hold @max values but there were @count uploaded. The following files have been omitted as a result: %list.', $args);
        \Drupal::messenger()->addWarning($message);
        $values['fids'] = array_slice($values['fids'], 0, $keep);
        NestedArray::setValue($form_state->getValues(), $element['#parents'], $values);
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.