datafield-1.x-dev/src/Plugin/DataField/FieldFormatter/TextTrimmedFormatter.php
src/Plugin/DataField/FieldFormatter/TextTrimmedFormatter.php
<?php
namespace Drupal\datafield\Plugin\DataField\FieldFormatter;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\datafield\Plugin\DataFieldFormatterInterface;
/**
* Plugin implementation of the 'text_trimmed' formatter.
*
* Note: This class also contains the implementations used by the
* 'text_summary_or_trimmed' formatter.
*
* @see \Drupal\text\Field\Formatter\TextSummaryOrTrimmedFormatter
*/
#[FieldFormatter(
id: 'text_trimmed',
label: new TranslatableMarkup('Trimmed'),
field_types: ['text', 'string'],
)]
class TextTrimmedFormatter implements DataFieldFormatterInterface {
use StringTranslationTrait;
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'trim_length' => '600',
];
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$settings = $form['#settings'];
$label = $form['#machine_name'];
$element['trim_length'] = [
'#title' => $this->t('Trimmed limit'),
'#type' => 'number',
'#field_suffix' => $this->t('characters'),
'#default_value' => $settings['trim_length'] ?? self::defaultSettings()['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' => $label]),
'#min' => 1,
];
return $element;
}
/**
* {@inheritdoc}
*/
public function settingsSummary($settings = []) {
$summary = [];
$settings += self::defaultSettings();
$summary[] = $this->t('Trimmed limit: @trim_length characters', ['@trim_length' => $settings['trim_length']]);
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements($item, $langcode) {
if (is_null($item->value)) {
return $item->value;
}
$trim_length = $item->settings['trim_length'] ?? self::defaultSettings()['trim_length'];
$output = [
'#type' => 'processed_text',
'#text' => $item->value,
'#format' => $item->format ?? 'full_html',
'#langcode' => $langcode,
'#text_summary_trim_length' => $trim_length,
];
if (!empty($trim_length)) {
unset($output['#text_summary_trim_length']);
}
return $output;
}
}
