Score:0

Using FileSystemInterface::EXISTS_REPLACE in a form to replace files if they already exist

cn flag

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);
    }
  }
No Sssweat avatar
ua flag
Here is an example of a D9 patch https://www.drupal.org/files/issues/2020-02-21/deprecated_code-3115151-3.patch
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.