drupalField Formatter


Introduction

A field formatter specifies the way a field is rendered in Drupal templates. The formatter used by each field can be configured in the Manage display tab associated with the entity type that you are configuring.

Fields can have different formatters depending on the view mode that is being displayed which allows you to control how a field is rendered in different parts of your website.

Remarks

Some things are important to consider when implementing a Field Formatter.

The implementation of your formatter must be inside your module in the folder src/Plugin/Field/FieldFormatter. The annotations are also critical as they identify your module and which field types it's applicable to.

In this example, this formatter is applicable only to fields of the type email. You can apply your formatter to a number of fields if necessary. If your formatter would, for whatever reason, be applicable to email and date fields:

field_type = {
  "email",
  "date",
}

One pitfall I've faced when first implementing field formatters with settings is that the settings weren't saved when changed. There is no explicit save method and the solution is to implement the defaultSettings() method and specify the field names that make up your configuration form. Also don't forget to set the #default_value in the settingsForm method.

If you want to have a specific TWIG template for your formatter it's as simple as configuring a #theme key while building the render array in the viewElements method then in your .module file implement hook_theme

function obfuscator_field_formatter_theme() {
  return [
    'obfuscator_field_formatter' => [
      'variables' => array('title' => NULL, 'url' => NULL),
      'template' => 'obfuscator-field-formatter'
    ],
  ];
}

Then create the templates folder in the root of your module and have a file named obfuscator-field-formatter.twig.html where you output the markup you need. In this example the variables the from the render #title and #url will be available.