You are here

public function AdvancedTextFormatter::viewElements in Advanced Text Formatter 8

Same name and namespace in other branches
  1. 2.1.x src/Plugin/Field/FieldFormatter/AdvancedTextFormatter.php \Drupal\advanced_text_formatter\Plugin\Field\FieldFormatter\AdvancedTextFormatter::viewElements()
  2. 2.0.x src/Plugin/Field/FieldFormatter/AdvancedTextFormatter.php \Drupal\advanced_text_formatter\Plugin\Field\FieldFormatter\AdvancedTextFormatter::viewElements()

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/AdvancedTextFormatter.php, line 259

Class

AdvancedTextFormatter
Plugin implementation of the 'advanced_text_formatter' formatter.

Namespace

Drupal\advanced_text_formatter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $token_data = [
    'user' => \Drupal::currentUser(),
    $items
      ->getEntity()
      ->getEntityTypeId() => $items
      ->getEntity(),
  ];
  foreach ($items as $delta => $item) {
    if ($this
      ->getSetting('use_summary') && !empty($item->summary)) {
      $output = $item->summary;
    }
    else {
      $output = $item->value;
    }
    if ($this
      ->getSetting('token_replace')) {
      $output = \Drupal::token()
        ->replace($output, $token_data);
    }
    switch ($this
      ->getSetting('filter')) {
      case static::FORMAT_DRUPAL:
        $output = check_markup($output, $this
          ->getSetting('format'), $item
          ->getLangcode());
        break;
      case static::FORMAT_PHP:
        $output = Xss::filter($output, $this
          ->getSetting('allowed_html'));
        if ($this
          ->getSetting('autop')) {
          $output = _filter_autop($output);
        }
        break;
      case static::FORMAT_INPUT:
        $output = check_markup($output, $item->format, $item
          ->getLangcode());
        break;
    }
    if ($this
      ->getSetting('trim_length') > 0) {
      $options = [
        'word_boundary' => $this
          ->getSetting('word_boundary'),
        'max_length' => $this
          ->getSetting('trim_length'),
        'ellipsis' => $this
          ->getSetting('ellipsis'),
      ];
      $output = advanced_text_formatter_trim_text($output, $options);
    }
    $elements[$delta] = [
      '#markup' => $output,
      '#langcode' => $item
        ->getLangcode(),
    ];
  }
  return $elements;
}