function TextTrimmedFormatter::viewElements

Same name in other branches
  1. 9 core/modules/text/src/Plugin/Field/FieldFormatter/TextTrimmedFormatter.php \Drupal\text\Plugin\Field\FieldFormatter\TextTrimmedFormatter::viewElements()
  2. 10 core/modules/text/src/Plugin/Field/FieldFormatter/TextTrimmedFormatter.php \Drupal\text\Plugin\Field\FieldFormatter\TextTrimmedFormatter::viewElements()
  3. 11.x core/modules/text/src/Plugin/Field/FieldFormatter/TextTrimmedFormatter.php \Drupal\text\Plugin\Field\FieldFormatter\TextTrimmedFormatter::viewElements()

Overrides FormatterInterface::viewElements

File

core/modules/text/src/Plugin/Field/FieldFormatter/TextTrimmedFormatter.php, line 70

Class

TextTrimmedFormatter
Plugin implementation of the 'text_trimmed' formatter.

Namespace

Drupal\text\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    $render_as_summary = function (&$element) {
        // Make sure any default #pre_render callbacks are set on the element,
        // because text_pre_render_summary() must run last.
        $element += \Drupal::service('element_info')->getInfo($element['#type']);
        // Add the #pre_render callback that renders the text into a summary.
        $element['#pre_render'][] = [
            TextTrimmedFormatter::class,
            'preRenderSummary',
        ];
        // Pass on the trim length to the #pre_render callback via a property.
        $element['#text_summary_trim_length'] = $this->getSetting('trim_length');
    };
    // The ProcessedText element already handles cache context & tag bubbling.
    // @see \Drupal\filter\Element\ProcessedText::preRenderText()
    foreach ($items as $delta => $item) {
        $elements[$delta] = [
            '#type' => 'processed_text',
            '#text' => NULL,
            '#format' => $item->format,
            '#langcode' => $item->getLangcode(),
        ];
        if ($this->getPluginId() == 'text_summary_or_trimmed' && !empty($item->summary)) {
            $elements[$delta]['#text'] = $item->summary;
        }
        else {
            $elements[$delta]['#text'] = $item->value;
            $render_as_summary($elements[$delta]);
        }
    }
    return $elements;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.