function FileExampleSubmitHandlerHelper::handleFileDelete
Submission handler to delete a file.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
File
-
modules/
file_example/ src/ FileExampleSubmitHandlerHelper.php, line 357
Class
- FileExampleSubmitHandlerHelper
- A submit handler helper class for the file_example module.
Namespace
Drupal\file_exampleCode
public function handleFileDelete(array &$form, FormStateInterface $form_state) {
$form_values = $form_state->getValues();
$uri = $form_values['file_ops_file'];
// Since we don't know if the file is managed or not, look in the database
// to see. Normally, code would be working with either managed or unmanaged
// files, so this is not a typical situation.
$file_object = $this->fileHelper
->getManagedFile($uri);
if (!empty($file_object)) {
// While FALSE is expected to be returned on failure, an exception can be
// thrown on certain cache states.
try {
$file_object->delete();
$this->messenger
->addMessage($this->t('Successfully deleted the managed file %uri', [
'%uri' => $uri,
]));
$this->stateHelper
->setDefaultFile($uri);
} catch (\Exception $e) {
$this->messenger
->addError($this->t('Failed deleting managed file %uri: @result', [
'%uri' => $uri,
'@result' => $e->getMessage(),
]));
}
}
else {
$result = $this->fileSystem
->delete($uri);
if ($result) {
$this->messenger
->addMessage($this->t('Successfully deleted unmanaged file %uri', [
'%uri' => $uri,
]));
$this->stateHelper
->setDefaultFile($uri);
}
else {
$this->messenger
->addError($this->t('Failed deleting unmanaged file %uri', [
'%uri' => $uri,
]));
}
}
}