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:
- FileSystemInterface::saveData(), which takes a buffer and saves it to a named file, but does not create any kind of tracking record in the database. This example uses FileSystemInterface::EXISTS_REPLACE for the third argument, meaning that if there's an existing file at this location, it should be replaced.
- file_create_url(), which converts a URI in the form public://junk.txt or
private://something/test.txt into a URL like
http://example.com/sites/default/files/junk.txt.
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_exampleCode
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');
}
}