I have a form set up in the admin menu that allows a person to upload a file, like a picture. That file is then used in the custom module elsewhere. I want to be able to replace that file if they upload it again. I believe I can use FileSystemInterface::EXISTS_REPLACE
in the form to do this, but I can't find documentation on how to exactly. Is there any examples of this being implemented? Please let me know if you'd like to see the form or any other code, but I don't think it's necessary. Thanks!
Edit, I've seen some documentation from last year saying it isn't possible to replace uploaded files with ones of the same name. I'm wondering if this is still true as of April 2022.
Here is where the image is uploaded in the form:
$form['upload']['sound_dir'] = [
'#type' => 'managed_file',
'#upload_location' => 'public://',
'#required' => FALSE,
'#multiple' => FALSE,
'#description' => t('Allowed extensions: mp3 wav'),
'#upload_validators' => [
'file_validate_extensions' => array('mp3 wav'),
'file_validate_size' => array(25600000)
],
'#title' => t('Upload a sound file:')
];
And the submit:
public function submitForm(array &$form, FormStateInterface $form_state) {
$file_data = $form_state->getValue(['upload' => 'sound_dir']);
if ($file_data != null) {
$file = \Drupal\file\Entity\File::load( $file_data[0], );
$file_name = $file->getFilename();
$uri = $file->getFileUri();
$url = \Drupal\Core\Url::fromUri(file_create_url($uri))->toString();
$file->setPermanent();
$file->save();
$this->configFactory->getEditable(static::SETTINGS)
->set('pathToSound', $url)
->save();
parent::submitForm($form, $form_state);
}
}