function ManagedFileElementHelper::managedFileSaveUpload
Saves any files that have been uploaded into a managed_file element.
Parameters
array $element: The FAPI element whose values are being saved.
\Drupal\Core\Form\FormStateInterface $formState: The current state of the form.
Return value
array<int, FileInterface>|false An array of file entities for each file that was saved, keyed by its file ID. Each array element contains a file entity. Function returns FALSE if upload directory could not be created or no files were uploaded.
File
-
core/
modules/ file/ src/ Upload/ ManagedFileElementHelper.php, line 138
Class
- ManagedFileElementHelper
- Helper class for ManagedFile element form file uploads.
Namespace
Drupal\file\UploadCode
public function managedFileSaveUpload(array $element, FormStateInterface $formState) : array|false {
$uploadName = implode('_', $element['#parents']);
$fileUpload = $this->uploadedFilesExtractor
->extractUploadedFiles($uploadName);
$destination = $element['#upload_location'] ?? NULL;
if (isset($destination) && !$this->fileSystem
->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY)) {
($this->logger)()
->notice('The upload directory %directory for the file field %name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.', [
'%directory' => $destination,
'%name' => $element['#field_name'],
]);
$formState->setError($element, $this->t('The file could not be uploaded.'));
return FALSE;
}
// Save attached files to the database.
$filesUploaded = $element['#multiple'] && count(array_filter($fileUpload)) > 0;
$filesUploaded |= !$element['#multiple'] && !empty($fileUpload);
if ($filesUploaded) {
if (!$files = $this->saveFileUploads($element, $formState)) {
($this->logger)()
->notice('The file upload failed. %upload', [
'%upload' => $uploadName,
]);
return [];
}
// Value callback expects FIDs to be keys.
$files = array_filter($files);
$fids = array_map(function ($file) {
return $file->id();
}, $files);
return empty($files) ? [] : array_combine($fids, $files);
}
return [];
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.