Mikhail Ismajlov 10/02/2019

In this article we will consider Field Formatters, that allow us to edit the display of fields and display them on the page. 

In past articles, we created field type Link, in this article we will look at how these fields are displayed on the page and which class is responsible for it. Each field that you add through Drupal can be displayed on the page and edit its settings on the page Manage display. 

manage display

In the column Format You can choose how to display the field. This column is formed due to Field Formatter classes. Let's look at the class from the module Link, which displays the link to the page:

core/modules/link/src/Plugin/Field/FieldFormatter/LinkFormatter.php

The class annotation shows what type of field this formatter belongs to.

/**
 * Plugin implementation of the 'link' formatter.
 *
 * @FieldFormatter(
 *   id = "link",
 *   label = @Translation("Link"),
 *   field_types = {
 *     "link"
 *   }
 * )
 */

In this file, we are primarily interested in the method viewElements(), this method is responsible for outputting data to the page. Note that the formatter does not send requests to the database, it takes data from a variable $items. Rendered data from the entity is passed to $items. Thus, we have a separation of the responsibility of the classes for data entry Field Widget, data storage Field Storage and data output Field Formatter. This is very convenient because you can cache data at different levels. For example, if the output or the Field Formatter settings have changed, it makes no sense to reset the cache nodes, because the data does not change, but only their output changes. It is also convenient for debating and adding new functionality. If you only need to change the output, you add a new Field Formater for the field type and write your output.

Also, the LinkFormatter class has the settingsForm() method, which is responsible for configuring the formatter on the Manage display page. Through the Form API you can add settings fields for the field and then store these settings in the configuration.

The Link module has another formatter:

core/modules/link/src/Plugin/Field/FieldFormatter/LinkSeparateFormatter.php

It is inherited from the usual LinkFormatter, but with one difference, a separate template is connected for this formatter:

core/modules/link/templates/link-formatter-link-separate.html.twig

Thus, HTML to output the field is obtained by passing through the template. And the formatter only forms a file $element, where through $delta write data for each of the values of the multiple field.

As you can see Field API is quite simple and convenient to use in the next article we will write our own type of field with Storage, Widget, Formatter.