Creating a custom field formatter

Field formatters define the way in which a field type will be presented. These formatters return the render array information to be processed by the theming layer. Field formatters are configured on the display mode interfaces.

In this recipe, we will create a formatter for the field created in the Creating a custom field type recipe in this chapter. The field formatter will display the first and last names with some settings.

Getting ready

Create a new module like the one existing in the first recipe. We will refer to the module as mymodule throughout the recipe. Use your module's appropriate name.

How to do it…

  1. We need to create the src/Plugin/Field/FieldFormatter directory in the module's base location. The Field module discovers field formatters in the PluginField FieldFormatter namespace.
  2. Create a RealNameFormatter.php file in the newly created directory so that we can define the RealNameFormatter class. This will provide a custom form element to display the field's values:
    How to do it…
  3. The RealNameFormatter class will extend the DrupalCoreFieldFormatterBase class:
    <?php
    
    /**
     * @file
     * Contains DrupalmymodulePluginFieldFieldFormatterRealNameFormatter
     */
    
    namespace DrupalmymodulePluginFieldFieldFormatter;
    
    use DrupalCoreFieldFormatterBase;
    use DrupalCoreFieldFieldItemListInterface;
    
    class RealNameFormatter extends FormatterBase {
    
    }
  4. Field formatters are like annotated plugins. Annotated plugins use documentation blocks to provide details of the plugin. We will provide the field widget's identifier, label, and supported field types:
    <?php
    
    /**
     * @file
     * Contains DrupalmymodulePluginFieldFieldFormatterRealNameFormatter
     */
    
    namespace DrupalmymodulePluginFieldFieldFormatter;
    
    use DrupalCoreFieldFormatterBase;
    use DrupalCoreFieldFieldItemListInterface;
    
    /**
     * Plugin implementation of the 'realname_one_line' formatter.
     *
     * @FieldFormatter(
     *   id = "realname_one_line",
     *   label = @Translation("Real name (one line)"),
     *   field_types = {
     *     "realname"
     *   }
     * )
     */
    
    class RealNameFormatter extends FormatterBase {
    
    }
  5. We need to implement the viewElements method to satisfy the DrupalCoreFieldFormatterInferface interface. This is used to render the field data:
      /**
       * {@inheritdoc}
       */
      public function viewElements(FieldItemListInterface $items, $langcode) {
        $element = [];
    
        foreach ($items as $delta => $item) {
          $element[$delta] = array(
            '#markup' => $this->t('@first @last', array(
                '@first' => $item->first_name,
                '@last' => $item->last_name,
              )
            ),
          );
        }
        return $element;
      }
  6. Next, we need to modify our original RealName field type's plugin class in order to use the default formatter that we created. Update the default_formatter annotation property as realname_one_line:
    /**
     * Plugin implementation of the 'realname' field type.
     *
     * @FieldType(
     *   id = "realname",
     *   label = @Translation("Real name"),
     *   description = @Translation("This field stores a first and last name."),
     *   category = @Translation("General"),
     *   default_widget = " string_textfield ",
     *   default_formatter = "realname_one_line"
     * )
     */
  7. Rebuild Drupal's cache so that the plugin system can discover the new field widget.
  8. Update an entity view mode with a Real name field to use the Real name (one line) formatter:
    How to do it…

How it works…

Drupal core defines a plugin.manager.field.formatter service. By default, this is handled through the DrupalCoreFieldFormatterPluginManager class. This plugin manager defines the field formatter plugins that should be in the Plugin/Field/FieldFormatter namespace, and all the classes in this namespace will be loaded and assumed to be field formatter plugins.

The manager's definition also sets DrupalCoreFieldFormatterInterface as the expected interface that all field formatter plugins will implement. This is why most field formatters extend DrupalCoreFieldFormatterBase to meet these method requirements.

As field formatters are annotated plugins, the manager provides DrupalCoreFieldAnnotationFieldFormatter as the class that fulfills the annotation definition.

The entity view display system uses the plugin.manager.field.formatter service to load field definitions and add the field's render array, returned from the viewElements method, to the entity view render array.

There's more

Formatter settings and summary

The DrupalCoreFieldFormatterInterface interface defines three methods that can be overridden to provide a settings form and a summary of the current settings:

  • defaultSettings: This returns an array of the setting keys and default values
  • settingsForm: This returns a Form API array that is used for the settings form
  • settingsSummary: This allows an array of strings to be returned and displayed on the manage display form for the field

Settings can be used to alter how the formatter displays information. For example, these methods can be implemented to provide settings to hide or display the first or last name.

See also

  • The Creating a custom plugin type recipe of this chapter
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset