Drupal 8 Custom Media Field Formatter

One or two weeks ago I stumbled upon Mark Conroy’s blog post about accessing the URL of a Media file in a Twig template. And I initially thought to myself: I’d write a field formatter for that.

Don’t get me wrong! Mark’s findings are very useful, as it can sometimes become pretty fiddly when you try to access certain things from inside Drupal’s Twig templates. So you’d better bookmark this gem!

On the other hand, overriding field formatters that way en masse can make your Drupal back-end quite useless in the end. As no matter what Display Settings you’ve chosen for a field, if it gets overridden by a template anyways, these settings won’t have any effect. It also may unintentionally raise maintenance efforts further down the road.

Keep the UI intact!

Keep the UI intact!

By providing your own field formatter, you can keep the admin experience intact and still have full control over the markup. Win-win! So, here comes a very basic example that provides an inline_template render element. But you can easily implement your own hook_theme to provide a distinct Twig template as well. All Mark needed was to get hold of 3 simple things (the media item, the file behind it, and the file URL) and then output the result. Done!

Fully working module can be found on GitHub. Further reading on drupal.org: Create a custom field formatter.