Loading...

Drupal 8 Field Formatter

A Field Formatter provides an easy way to format fields in Drupal. Many come with Drupal core and are available for use after site installation. Some common Field Formatters include Plain Text, Label, Entity ID, and Rendered Entity to name a few.

Control How Fields Render

Field Formatters render fields in various ways. For example, I may want to render an email field as a clickable link that will open up an email client. By default, email fields have two field formatters that can be used, Plain Text and Email. The first option would of course just render the email as raw text printed to the page where the second would give us the result we're looking for.

To edit the formatter for a field, follow these steps:

  • Go to the Manage Display page for the entity bundle you are working with. Ex: Structure -> Content Types -> Basic Page -> Manage Display.

Drupal 8 Field Formatter

  • In the column labeled Format click the dropdown for the field you would like to edit.

Drupal 8 Field Formatter

Field Formatters also have specific settings you can use to fine tune the fields rendered results. These settings can be accessed and edited by clicking on the cog icon at the end of the row of that field. In the case of formatters like the Email formatter, there are few or no settings at all. Of course, like many things in Drupal, you can make field formatters of your own!

How Do You Make A Field Formatter?

To make a field formatter you must:

  1. Create a module.
  2. Create a file with a class under the Drupal\{module_name}\Plugin\Field\FieldFormatter namespace. Be sure to use the appropriate folder structure ({module_name}/src/Plugin/Field/FieldFormatter).
  3. For a basic field formatter, make sure it extends the FormatterBase class. Dont forget to add use Drupal\Core\Field\FormatterBase; after the namespace. (Note: Field Formatter class names should be named according to its functionality and have "Formatter" as a suffix. An example would be BasicStringFormatter which is responsible for the Plain Text formatter.)
  4. As the namespace suggested, FieldFormatters are a type of Drupal Plugin. That means we'd need to make a plugin annotation. Basic information to include would be an id, a label, and field types that thisformatter can be used on. Here is an example implemented by the Basic String Formatter (Plain Text).
    /**
     * Plugin implementation of the 'basic_string' formatter.
     *
     * @FieldFormatter(
     *   id = "basic_string",
     *   label = @Translation("Plain text"),
     *   field_types = {
     *     "string_long",
     *     "email"
     *   },
     *   quickedit = {
     *     "editor" = "plain_text"
     *   }
     * )
     */
  5. The last step is to setup the logic responsible for rendering the field. The viewElements method can help us with this. We have access to it from the FormatterInterface implemented by the FormatterBase class. The FieldItemListInterface must be used for the $items parameter. Be sure to add use Drupal\Core\Field\FieldItemListInterface; This function allows you to render field items, whether one or many, how ever you like. This may be something as simple as adding some markup to the output to using that output in JS to do something interesting! Here is how the Basic String Formatter uses this method:
    public function viewElements(FieldItemListInterface $items, $langcode) {
      $elements = [];
    
      foreach ($items as $delta => $item) {
        // The text value has no text format assigned to it, so the user input
        // should equal the output, including newlines.
        $elements[$delta] = [
          '#type' => 'inline_template',
          '#template' => '{{ value|nl2br }}',
          '#context' => ['value' => $item->value],
        ];
      }
    
      return $elements;
    }

Once you follow those steps, enable the module (if you have not already), and clear cache, you will have a basic working field formatter for use on the fields it is intended for.

For more information on Field Formatters, such as how to create formatter settings and more, check out the offical documentation on drupal.org.