public static function FileWidget::validateMultipleCount in Drupal 10
Same name and namespace in other branches
- 8 core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php \Drupal\file\Plugin\Field\FieldWidget\FileWidget::validateMultipleCount()
- 9 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 341
Class
- FileWidget
- Plugin implementation of the 'file_generic' widget.
Namespace
Drupal\file\Plugin\Field\FieldWidgetCode
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 = 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::messenger()
->addWarning($message);
$values['fids'] = array_slice($values['fids'], 0, $keep);
NestedArray::setValue($form_state
->getValues(), $element['#parents'], $values);
}
}