You are here

public function CustomFormatters::viewElements in Custom Formatters 8.3

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/CustomFormatters.php, line 23

Class

CustomFormatters
Plugin implementation of the 'text_default' formatter.

Namespace

Drupal\custom_formatters\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {

  /** @var \Drupal\custom_formatters\FormatterInterface $formatter */
  $formatter = \Drupal::entityTypeManager()
    ->getStorage('formatter')
    ->load($this
    ->getPluginDefinition()['formatter']);
  $element = $formatter
    ->getFormatterType()
    ->viewElements($items, $langcode);
  if (!$element) {

    // @TODO - Fail better.
    return [];
  }

  // Transform strings into a renderable element.
  if (is_string($element)) {
    $element = [
      '#markup' => $element,
    ];
  }

  // Ensure we have a nested array.
  if (is_array($element) && !Element::children($element)) {
    $element = [
      $element,
    ];
  }
  foreach (Element::children($element) as $delta) {
    $element[$delta]['#cf_options'] = isset($display['#cf_options']) ? $display['#cf_options'] : [];
    $element[$delta]['#cache']['tags'] = $formatter
      ->getCacheTags();
  }

  // Allow third party integrations a chance to alter the element.
  \Drupal::service('plugin.manager.custom_formatters.formatter_extras')
    ->alter('formatterViewElements', $formatter, $element);
  return $element;
}