You are here

public static function FileWidget::validateMultipleCount in Zircon Profile 8.0

Same name and namespace in other branches
  1. 8 core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php \Drupal\file\Plugin\Field\FieldWidget\FileWidget::validateMultipleCount()

Form element validation callback for upload element on file widget. Checks if user has uploaded more files than allowed.

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

File

core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php, line 334
Contains \Drupal\file\Plugin\Field\FieldWidget\FileWidget.

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) {
  $parents = $element['#parents'];
  $values = NestedArray::getValue($form_state
    ->getValues(), $parents);
  array_pop($parents);
  $current = count(Element::children(NestedArray::getValue($form, $parents))) - 1;
  $field_storage_definitions = \Drupal::entityManager()
    ->getFieldStorageDefinitions($element['#entity_type']);
  $field_storage = $field_storage_definitions[$element['#field_name']];
  $uploaded = count($values['fids']);
  $count = $uploaded + $current;
  if ($count > $field_storage
    ->getCardinality()) {
    $keep = $uploaded - $count + $field_storage
      ->getCardinality();
    $removed_files = array_slice($values['fids'], $keep);
    $removed_names = array();
    foreach ($removed_files as $fid) {
      $file = File::load($fid);
      $removed_names[] = $file
        ->getFilename();
    }
    $args = array(
      '%field' => $field_storage
        ->getName(),
      '@max' => $field_storage
        ->getCardinality(),
      '@count' => $uploaded,
      '%list' => implode(', ', $removed_names),
    );
    $message = t('Field %field can only hold @max values but there were @count uploaded. The following files have been omitted as a result: %list.', $args);
    drupal_set_message($message, 'warning');
    $values['fids'] = array_slice($values['fids'], 0, $keep);
    NestedArray::setValue($form_state
      ->getValues(), $element['#parents'], $values);
  }
}