function FileExampleSubmitHandlerHelper::handleManagedFile
Submit handler to write a managed file.
A "managed file" is a file that Drupal tracks as a file entity. It's the standard way Drupal manages files in file fields and elsewhere.
The key functions used here are:
- file_save_data(), which takes a buffer and saves it to a named file and also creates a tracking record in the database and returns a file object. In this function we use FileSystemInterface::EXISTS_RENAME (the default) as the argument, which means that if there's an existing file, create a new non-colliding filename and use it.
- 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 76
Class
- FileExampleSubmitHandlerHelper
- A submit handler helper class for the file_example module.
Namespace
Drupal\file_exampleCode
public function handleManagedFile(array &$form, FormStateInterface $form_state) {
$form_values = $form_state->getValues();
$data = $form_values['write_contents'];
$uri = !empty($form_values['destination']) ? $form_values['destination'] : NULL;
// Managed operations work with a file object.
$file_object = $this->fileRepository
->writeData($data, $uri, FileSystemInterface::EXISTS_RENAME);
if (!empty($file_object)) {
$url = $this->fileHelper
->getExternalUrl($file_object);
$this->stateHelper
->setDefaultFile($file_object->getFileUri());
$file_data = $file_object->toArray();
if ($url) {
$this->messenger
->addMessage($this->t('Saved managed file: %file to destination %destination (accessible via <a href=":url">this URL</a>, actual uri=<span id="uri">@uri</span>)', [
'%file' => print_r($file_data, TRUE),
'%destination' => $uri,
'@uri' => $file_object->getFileUri(),
':url' => $url->toString(),
]));
}
else {
// This Uri is not routable, so we cannot give a link to it.
$this->messenger
->addMessage($this->t('Saved managed file: %file to destination %destination (no URL, since this stream type does not support it)', [
'%file' => print_r($file_data, TRUE),
'%destination' => $uri,
'@uri' => $file_object->getFileUri(),
]));
}
}
else {
$this->messenger
->addMessage($this->t('Failed to save the managed file'), 'error');
}
}