Create a custom field formatter

Last updated on
10 January 2017

The field formatter formats the field data to be viewed by the end user. Field formatters are defined as plugins, so it's a good idea to familiarize yourself with the Plugin API before diving in to writing a new field type.

Field formatter class

File: /modules/random/src/Plugin/Field/FieldFormatter/RandomDefaultFormatter.php

<?php

/**
 * @file
 * Contains \Drupal\Random\Plugin\Field\FieldFormatter\RandomDefaultFormatter.
 */

namespace Drupal\random\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;

/**
 * Plugin implementation of the 'Random_default' formatter.
 *
 * @FieldFormatter(
 *   id = "Random_default",
 *   label = @Translation("Random text"),
 *   field_types = {
 *     "Random"
 *   }
 * )
 */
class RandomDefaultFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = array();
    $settings = $this->getSettings();

    $summary[] = t('Displays the random string.');

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = array();

    foreach ($items as $delta => $item) {
      // Render each element as markup.
      $element[$delta] = array(
        '#type' => 'markup',
        '#markup' => $item->value,
      );
    }

    return $element;
  }
}