TextTrimmedFormatter.php 2.23 KB
Newer Older
1 2 3 4 5
<?php

/**
 * @file
 *
6
 * Contains \Drupal\text\Plugin\field\formatter\TextTrimmedFormatter.
7 8 9
 */
namespace Drupal\text\Plugin\field\formatter;

10
use Drupal\field\Annotation\FieldFormatter;
11 12 13
use Drupal\Core\Annotation\Translation;
use Drupal\field\Plugin\Type\Formatter\FormatterBase;
use Drupal\Core\Entity\EntityInterface;
14
use Drupal\Core\Entity\Field\FieldInterface;
15 16 17 18 19 20 21 22 23

/**
 * 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
 *
24
 * @FieldFormatter(
25 26 27 28 29 30 31 32 33
 *   id = "text_trimmed",
 *   label = @Translation("Trimmed"),
 *   field_types = {
 *     "text",
 *     "text_long",
 *     "text_with_summary"
 *   },
 *   settings = {
 *     "trim_length" = "600"
34 35 36
 *   },
 *   edit = {
 *     "editor" = "form"
37 38 39 40 41 42
 *   }
 * )
 */
class TextTrimmedFormatter extends FormatterBase {

  /**
43
   * {@inheritdoc}
44 45 46 47 48 49 50 51 52 53 54 55 56
   */
  public function settingsForm(array $form, array &$form_state) {
    $element['trim_length'] = array(
      '#title' => t('Trim length'),
      '#type' => 'number',
      '#default_value' => $this->getSetting('trim_length'),
      '#min' => 1,
      '#required' => TRUE,
    );
    return $element;
  }

  /**
57
   * {@inheritdoc}
58 59
   */
  public function settingsSummary() {
60 61 62
    $summary = array();
    $summary[] = t('Trim length: @trim_length', array('@trim_length' => $this->getSetting('trim_length')));
    return $summary;
63 64 65
  }

  /**
66
   * {@inheritdoc}
67
   */
68
  public function viewElements(EntityInterface $entity, $langcode, FieldInterface $items) {
69 70
    $elements = array();

71
    $text_processing = $this->getFieldSetting('text_processing');
72
    foreach ($items as $delta => $item) {
73 74
      if ($this->getPluginId() == 'text_summary_or_trimmed' && !empty($item->summary)) {
        $output = text_sanitize($text_processing, $langcode, $item->getValue(TRUE), 'summary');
75 76
      }
      else {
77 78
        $output = text_sanitize($text_processing, $langcode, $item->getValue(TRUE), 'value');
        $output = text_summary($output, $text_processing ? $item->format : NULL, $this->getSetting('trim_length'));
79 80 81 82 83 84 85 86
      }
      $elements[$delta] = array('#markup' => $output);
    }

    return $elements;
  }

}