class TextTrimmedFormatter

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

Plugin implementation of the 'text_trimmed' formatter.

Note: This class also contains the implementations used by the 'text_summary_or_trimmed' formatter.

Hierarchy

Expanded class hierarchy of TextTrimmedFormatter

See also

\Drupal\text\Field\Formatter\TextSummaryOrTrimmedFormatter

1 file declares its use of TextTrimmedFormatter
TestTextTrimmedFormatter.php in core/modules/field/tests/modules/field_plugins_test/src/Plugin/Field/FieldFormatter/TestTextTrimmedFormatter.php

File

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

Namespace

Drupal\text\Plugin\Field\FieldFormatter
View source
class TextTrimmedFormatter extends FormatterBase implements TrustedCallbackInterface {
    
    /**
     * {@inheritdoc}
     */
    public static function defaultSettings() {
        return [
            'trim_length' => '600',
        ] + parent::defaultSettings();
    }
    
    /**
     * {@inheritdoc}
     */
    public function settingsForm(array $form, FormStateInterface $form_state) {
        $element['trim_length'] = [
            '#title' => $this->t('Trimmed limit'),
            '#type' => 'number',
            '#field_suffix' => $this->t('characters'),
            '#default_value' => $this->getSetting('trim_length'),
            '#description' => $this->t('If the summary is not set, the trimmed %label field will end at the last full sentence before this character limit.', [
                '%label' => $this->fieldDefinition
                    ->getLabel(),
            ]),
            '#min' => 1,
            '#required' => TRUE,
        ];
        return $element;
    }
    
    /**
     * {@inheritdoc}
     */
    public function settingsSummary() {
        $summary = [];
        $summary[] = $this->t('Trimmed limit: @trim_length characters', [
            '@trim_length' => $this->getSetting('trim_length'),
        ]);
        return $summary;
    }
    
    /**
     * {@inheritdoc}
     */
    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;
    }
    
    /**
     * Pre-render callback: Renders a processed text element's #markup as a summary.
     *
     * @param array $element
     *   A structured array with the following key-value pairs:
     *   - #markup: the filtered text (as filtered by filter_pre_render_text())
     *   - #format: containing the machine name of the filter format to be used to
     *     filter the text. Defaults to the fallback format. See
     *     filter_fallback_format().
     *   - #text_summary_trim_length: the desired character length of the summary
     *     (used by text_summary())
     *
     * @return array
     *   The passed-in element with the filtered text in '#markup' trimmed.
     *
     * @see filter_pre_render_text()
     * @see text_summary()
     */
    public static function preRenderSummary(array $element) {
        $element['#markup'] = text_summary($element['#markup'], $element['#format'], $element['#text_summary_trim_length']);
        return $element;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function trustedCallbacks() {
        return [
            'preRenderSummary',
        ];
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
FormatterBase::$fieldDefinition protected property The field definition.
FormatterBase::$label protected property The label display setting.
FormatterBase::$settings protected property The formatter settings. Overrides PluginSettingsBase::$settings
FormatterBase::$viewMode protected property The view mode.
FormatterBase::create public static function Overrides ContainerFactoryPluginInterface::create 13
FormatterBase::getFieldSetting protected function Returns the value of a field setting.
FormatterBase::getFieldSettings protected function Returns the array of field settings.
FormatterBase::isApplicable public static function Overrides FormatterInterface::isApplicable 12
FormatterBase::prepareView public function Overrides FormatterInterface::prepareView 2
FormatterBase::view public function Overrides FormatterInterface::view 1
FormatterBase::__construct public function Constructs a FormatterBase object. 13
PluginInspectionInterface::getPluginDefinition public function Gets the definition of the plugin implementation. 6
PluginInspectionInterface::getPluginId public function Gets the plugin ID of the plugin instance. 2
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::calculateDependencies public function Overrides DependentPluginInterface::calculateDependencies 6
PluginSettingsBase::getSetting public function Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::onDependencyRemoval public function Overrides PluginSettingsInterface::onDependencyRemoval 3
PluginSettingsBase::setSetting public function Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
TextTrimmedFormatter::defaultSettings public static function Overrides PluginSettingsBase::defaultSettings
TextTrimmedFormatter::preRenderSummary public static function Pre-render callback: Renders a processed text element's #markup as a summary.
TextTrimmedFormatter::settingsForm public function Overrides FormatterBase::settingsForm
TextTrimmedFormatter::settingsSummary public function Overrides FormatterBase::settingsSummary
TextTrimmedFormatter::trustedCallbacks public static function Overrides TrustedCallbackInterface::trustedCallbacks
TextTrimmedFormatter::viewElements public function Overrides FormatterInterface::viewElements
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.

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