Drupal 8 has dramatically changed the process of creation of custom formatters and widgets. If in Drupal 7 this could have been done with hooks usage, then in the new version this process is similar to Ctools plugin writing. Further in this blog we will explain why.
In Drupal 8 hooks are replaced by class methods, and this actually means that the main file of the module (.module) can remain even empty. The use of classes means inheritance and it can be clearly seen in Drupal 8 core. E.g. image formatter inherits file formatter. Further we will deal with the process of creating one’s own formatter for the field.
First a web developer needs to create a folder for module plugins and to place all of them (formatters, widgets, etc.) to the separate files. The path will be the following:
example_module/lib/Drupal/example_module/Plugin/ field/FieldFormatter/ExampleFormatter.php
A large number of directories make immutable attributes of PSR-0 standard. On drupal.org there is a separate theme devoted to the discussion of this and similar PSR-4 standard as well as their relevance.
In Drupal 7 creation of one’s own formatters begins from hook_field_formatter_info(). But in the new version the most (if not all) of the info-hooks are replaced with annotations. In this case, the annotative class \Drupal\field\Annotation\FieldFormatter is used. Here is an example of plugin-style formatter:
<?php /** * Plugin implementation of the 'example_formatter' formatter * * @FieldFormatter( * id = "example_formatter", * label = @Translation("Example formatter"), * field_types = { * "text", * }, * settings = { * "trim_length" = "300", * }, * edit = { * "editor" = "form" * } * ) */ class ExampleFormatter extends FormatterBase { }