datafield-1.x-dev/src/Plugin/DataField/FieldFormatter/TextTwigFormatter.php

src/Plugin/DataField/FieldFormatter/TextTwigFormatter.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' formatter.
 *
 * Note: This class also contains the implementations used by the
 * 'text_twig' formatter.
 */
#[FieldFormatter(
  id: 'text_twig',
  label: new TranslatableMarkup('With twig text'),
  field_types: ['text', 'string'],
)]
class TextTwigFormatter implements DataFieldFormatterInterface {
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'trim_length' => '2000',
      'twig_template' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $settings = $form['#settings'];
    $settings += self::defaultSettings();
    $element['trim_length'] = [
      '#title' => $this->t('Trimmed limit'),
      '#type' => 'number',
      '#field_suffix' => $this->t('characters'),
      '#default_value' => $settings['trim_length'],
    ];
    $element['twig_template'] = [
      '#title' => $this->t('Template'),
      '#description' => $this->t('Variable {{value}}, {{settings}}, {{entity}}'),
      '#type' => 'textarea',
      '#default_value' => $settings['twig_template'],
    ];
    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) {
    $trim_length = $item->settings['trim_length'] ?? self::defaultSettings()['trim_length'];
    $template = $item->settings['twig_template'] ?? $item->value;
    $output = [
      '#type' => 'inline_template',
      '#template' => !empty($template) ? $template : $item->value,
      '#context' => (array) $item,
    ];
    if (!empty($trim_length)) {
      $output['#text_summary_trim_length'] = $trim_length;
    }
    return $output;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc