Question

I have a Content Type with a FileField (Image, in particular). When one of these values is deleted, then Drupal deletes the underlying file as well (as long as no other nodes reference the same file).

I don't want the underlying files to be deleted, I want them to remain in the filesystem. Are there any hooks or other techniques I can use to make sure it remains after its FileField value is deleted?

Was it helpful?

Solution 2

It's an ugly hack, but this is the simplest way I found to prevent a file from being deleted. It works by hooking file_delete and then removing the uri property from the $file variable. Without the uri, Drupal is unable to delete the file.

// Think twice before using this ugly hack.
// It probably breaks something and kills kittens.
function mymodule_file_delete($file) {
  $path = drupal_realpath($file->uri);
  if (!is_dir($path) && is_file($path)) {
    if (preg_match('/insert_regex_here/', $path)) {
      $file->uri = NULL;
    }
  }
}

The other alternatives I considered were:

  • Hacking core
    Although hacking core is taboo, it would be a cleaner solution than the hook I use above.
  • Using file_usage_add() on each file I want to retain
    Doesn't fit my use case very well - tens of thousands of files created and deleted independently of Drupal. Synchronizing all those files with file_usage_add would be daunting.
  • Use Media module to reference the file paths
    Media seems like overkill and it isn't stable yet. Plus I'm not sure if it would do what I need.
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top