function FileExampleSubmitHandlerHelper::handleUnmanagedFile

Submit handler to write an unmanaged file.

An unmanaged file is a file that Drupal does not track. A standard operating system file, in other words.

The key functions used here are:

Parameters

array $form: An associative array containing the structure of the form.

array &$form: The form array.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

File

modules/file_example/src/FileExampleSubmitHandlerHelper.php, line 136

Class

FileExampleSubmitHandlerHelper
A submit handler helper class for the file_example module.

Namespace

Drupal\file_example

Code

public function handleUnmanagedFile(array &$form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
    $data = $form_values['write_contents'];
    $destination = !empty($form_values['destination']) ? $form_values['destination'] : NULL;
    // With the unmanaged file we just get a filename back.
    $filename = $this->fileSystem
        ->saveData($data, $destination, FileSystemInterface::EXISTS_REPLACE);
    if ($filename) {
        $url = $this->fileHelper
            ->getExternalUrl($filename);
        $this->stateHelper
            ->setDefaultFile($filename);
        if ($url) {
            $this->messenger
                ->addMessage($this->t('Saved file as %filename (accessible via <a href=":url">this URL</a>, uri=<span id="uri">@uri</span>)', [
                '%filename' => $filename,
                '@uri' => $filename,
                ':url' => $url->toString(),
            ]));
        }
        else {
            $this->messenger
                ->addMessage($this->t('Saved file as %filename (not accessible externally)', [
                '%filename' => $filename,
                '@uri' => $filename,
            ]));
        }
    }
    else {
        $this->messenger
            ->addMessage($this->t('Failed to save the file'), 'error');
    }
}