Member-only story
How To Sanitise A File Name In Drupal
Using event subscriber
When adding a file field that users will use, you shouldn’t expect them to upload files with names that don’t contain strange characters or spaces, because they will often do it.
In most cases, you can just use the Transliteration module (https://www.drupal.org/project/transliteration), and that will take care of it. But if, like in my case, you need to rename the files to a specific format, you may want to create your own event subscriber.
To do so, follow these steps (replacing module_name with your actual module name):
- Create a modules/custom/module_name/module_name.services.yml:
module_name.file_upload_subscriber:
class: Drupal\module_name\EventSubscriber\FileUploadSubscriber
arguments: ['@transliteration']
tags:
- { name: event_subscriber }
2. Create a modules/custom/module_name/src/EventSubscriber/FileUploadSubscriber.php:
<?php
namespace Drupal\module_name\EventSubscriber;
use Drupal\Core\File\Event\FileUploadSanitizeNameEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Component\Transliteration\TransliterationInterface;
class FileUploadSubscriber implements EventSubscriberInterface {
/**
* The transliteration service.
*
* @var…