How To Replace Media in Drupal 8
Now that the media module is in core (watch our class on the Media Module here), we’re starting to see some contributed modules come along that help fill in some of the gaps. Not being able to replace an image, pdf, or video is one of the most notable issues with the Media module.
So if you had a PDF that gets occasional updates, the only recourse you would have is to upload a new version and then head over to every node where the pdf is used and change it out. There has to be a better way!
Well, now there is: the Media Entity File Replace module from Brian Osborne.
From The Module Description
This module allows content editors to easily replace the source files associated with file-based media types (like “Document”). The replacement file overwrites the existing file, keeping the same filename and path, which is usually what content editors want to do when performing a file replacement.
This module operates on the media entity level, meaning the file replacement is done by accessing the edit form for a media entity that has a file source field on it. If you’re using Drupal’s media module for document management, then this is what you want.
Without this module, content editors would typically try and replace a file by editing the media entity, using the “remove” button on the file widget, and uploading a new replacement file with the same filename. However, this does not work as intended, as Drupal will append a number to the end of the replacement file, like “_1” or “_2”, instead of actually overwriting the original. The only workaround is to delete the media entity, hope the site is configured to automatically delete unused files on cron runs, wait for that deletion to occur, and then upload a new document with the same filename.
Getting Started
Install the module as you would any other. That’s it! That’s all you need to do.
When editing a media entity, a new section will appear at the top of the editing area allowing you to upload a new version of the entity and the option to keep the file name. You’ll probably want to keep the filename more often than not so anywhere the entity is embedded will use the new version.
There are some things to note:
- As of this writing, the module is brand new – the Beta1 release was on January 1, 2020.
- It is not covered by the security advisory policy (as of yet)
- As such, you should be very careful and test before using this module in a production environment.
Brian Osborne is a Senior Web Developer at Princeton University and has contributed to a number of projects. He is also the creator of Layout Builder Styles, another module we covered in our Layout Builder class. Many thanks to Brian for creating and contributing this incredibly helpful add-on for the Media module!