function file_managed_file_save_upload

Same name in other branches
  1. 7.x modules/file/file.module \file_managed_file_save_upload()
  2. 9 core/modules/file/file.module \file_managed_file_save_upload()
  3. 8.9.x core/modules/file/file.module \file_managed_file_save_upload()
  4. 10 core/modules/file/file.module \file_managed_file_save_upload()

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 $form_state: The current state of the form.

Return value

array|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.

1 call to file_managed_file_save_upload()
ManagedFile::valueCallback in core/modules/file/src/Element/ManagedFile.php
Determines how user input is mapped to an element's #value property.

File

core/modules/file/file.module, line 686

Code

function file_managed_file_save_upload($element, FormStateInterface $form_state) {
    $upload_name = implode('_', $element['#parents']);
    $all_files = \Drupal::request()->files
        ->get('files', []);
    if (empty($all_files[$upload_name])) {
        return FALSE;
    }
    $file_upload = $all_files[$upload_name];
    $destination = $element['#upload_location'] ?? NULL;
    if (isset($destination) && !\Drupal::service('file_system')->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY)) {
        \Drupal::logger('file')->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'],
        ]);
        $form_state->setError($element, t('The file could not be uploaded.'));
        return FALSE;
    }
    // Save attached files to the database.
    $files_uploaded = $element['#multiple'] && count(array_filter($file_upload)) > 0;
    $files_uploaded |= !$element['#multiple'] && !empty($file_upload);
    if ($files_uploaded) {
        if (!($files = _file_save_upload_from_form($element, $form_state))) {
            \Drupal::logger('file')->notice('The file upload failed. %upload', [
                '%upload' => $upload_name,
            ]);
            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.