Creating Custom Field Formatters in Drupal 8

Originally published at: http://www.sitepoint.com/creating-custom-field-formatters-drupal-8/

With the introduction of annotated plugins, a lot has changed in Drupal 8. We have a more streamlined approach to describing and discovering pieces of functionality that extend the core. Along with many other components, the former Field API (part of the larger and consolidated Entity API) is now based on plugins.

In this tutorial we will go through defining a custom field formatter for an existing field (image). What we want to achieve is to make it possible to display an image with a small caption below it. This caption will be the title value assigned to the image if one exists.

The code we write here can be found in this repository as the image_title_caption module. But let’s see how we can get to that final result.

The module

Let us start by creating a new custom module (image_title_caption) with only one file:

image_title_caption.info.yml:

name: Image title caption
type: module
description: Uses the image title field as a caption
core: 8.x
dependencies:
  - image

Nothing out of the ordinary here. We can even enable the module already if we want.

Continue reading this article on SitePoint

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.