Version 1
[yaffs-website] / web / core / modules / text / src / Plugin / Field / FieldFormatter / TextTrimmedFormatter.php
1 <?php
2
3 namespace Drupal\text\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Field\FormatterBase;
6 use Drupal\Core\Field\FieldItemListInterface;
7 use Drupal\Core\Form\FormStateInterface;
8
9 /**
10  * Plugin implementation of the 'text_trimmed' formatter.
11  *
12  * Note: This class also contains the implementations used by the
13  * 'text_summary_or_trimmed' formatter.
14  *
15  * @see \Drupal\text\Field\Formatter\TextSummaryOrTrimmedFormatter
16  *
17  * @FieldFormatter(
18  *   id = "text_trimmed",
19  *   label = @Translation("Trimmed"),
20  *   field_types = {
21  *     "text",
22  *     "text_long",
23  *     "text_with_summary"
24  *   },
25  *   quickedit = {
26  *     "editor" = "form"
27  *   }
28  * )
29  */
30 class TextTrimmedFormatter extends FormatterBase {
31
32   /**
33    * {@inheritdoc}
34    */
35   public static function defaultSettings() {
36     return [
37       'trim_length' => '600',
38     ] + parent::defaultSettings();
39   }
40
41   /**
42    * {@inheritdoc}
43    */
44   public function settingsForm(array $form, FormStateInterface $form_state) {
45     $element['trim_length'] = [
46       '#title' => t('Trimmed limit'),
47       '#type' => 'number',
48       '#field_suffix' => t('characters'),
49       '#default_value' => $this->getSetting('trim_length'),
50       '#description' => 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()]),
51       '#min' => 1,
52       '#required' => TRUE,
53     ];
54     return $element;
55   }
56
57   /**
58    * {@inheritdoc}
59    */
60   public function settingsSummary() {
61     $summary = [];
62     $summary[] = t('Trimmed limit: @trim_length characters', ['@trim_length' => $this->getSetting('trim_length')]);
63     return $summary;
64   }
65
66   /**
67    * {@inheritdoc}
68    */
69   public function viewElements(FieldItemListInterface $items, $langcode) {
70     $elements = [];
71
72     $render_as_summary = function (&$element) {
73       // Make sure any default #pre_render callbacks are set on the element,
74       // because text_pre_render_summary() must run last.
75       $element += \Drupal::service('element_info')->getInfo($element['#type']);
76       // Add the #pre_render callback that renders the text into a summary.
77       $element['#pre_render'][] = [TextTrimmedFormatter::class, 'preRenderSummary'];
78       // Pass on the trim length to the #pre_render callback via a property.
79       $element['#text_summary_trim_length'] = $this->getSetting('trim_length');
80     };
81
82     // The ProcessedText element already handles cache context & tag bubbling.
83     // @see \Drupal\filter\Element\ProcessedText::preRenderText()
84     foreach ($items as $delta => $item) {
85       $elements[$delta] = [
86         '#type' => 'processed_text',
87         '#text' => NULL,
88         '#format' => $item->format,
89         '#langcode' => $item->getLangcode(),
90       ];
91
92       if ($this->getPluginId() == 'text_summary_or_trimmed' && !empty($item->summary)) {
93         $elements[$delta]['#text'] = $item->summary;
94       }
95       else {
96         $elements[$delta]['#text'] = $item->value;
97         $render_as_summary($elements[$delta]);
98       }
99     }
100
101     return $elements;
102   }
103
104   /**
105    * Pre-render callback: Renders a processed text element's #markup as a summary.
106    *
107    * @param array $element
108    *   A structured array with the following key-value pairs:
109    *   - #markup: the filtered text (as filtered by filter_pre_render_text())
110    *   - #format: containing the machine name of the filter format to be used to
111    *     filter the text. Defaults to the fallback format. See
112    *     filter_fallback_format().
113    *   - #text_summary_trim_length: the desired character length of the summary
114    *     (used by text_summary())
115    *
116    * @return array
117    *   The passed-in element with the filtered text in '#markup' trimmed.
118    *
119    * @see filter_pre_render_text()
120    * @see text_summary()
121    */
122   public static function preRenderSummary(array $element) {
123     $element['#markup'] = text_summary($element['#markup'], $element['#format'], $element['#text_summary_trim_length']);
124     return $element;
125   }
126
127 }