improvements-2.x-dev/src/Plugin/Field/FieldFormatter/TextReplaceFormatter.php
src/Plugin/Field/FieldFormatter/TextReplaceFormatter.php
<?php namespace Drupal\improvements\Plugin\Field\FieldFormatter; use Drupal\Core\Field\FieldItemListInterface; use Drupal\Core\Field\FormatterBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Render\Markup; use Drupal\improvements\ImprovementsHelper; /** * @FieldFormatter( * id = "text_replace", * label = @Translation("Template by RegExp"), * field_types = { * "text", * "text_long", * "text_with_summary", * "string", * }, * ) */ class TextReplaceFormatter extends FormatterBase { /** * {@inheritdoc} */ public static function defaultSettings(): array { return [ 'regexp' => '', 'template' => '', ] + parent::defaultSettings(); } /** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state): array { $elements['regexp'] = [ '#type' => 'textfield', '#title' => t('RegExp pattern'), '#default_value' => $this->getSetting('regexp'), '#description' => $this->t('Example: @example', ['@example' => Markup::create('<code>/(.+): (.+)/</code>')]), '#attributes' => [ 'style' => 'font-family:monospace;', ], ]; $elements['template'] = [ '#type' => 'textarea', '#title' => t('Template'), '#default_value' => $this->getSetting('template'), '#description' => $this->t('Example: @example', ['@example' => Markup::create('<code>' . htmlspecialchars('<b>$1</b>: $2') . '</code>')]), '#rows' => ImprovementsHelper::getTextareaRowsCount($this->getSetting('template'), 1), ]; return $elements; } /** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode): array { $elements = []; foreach ($items as $delta => $item) { $elements[$delta] = $this->viewElement($item); } return $elements; } /** * Return element build. */ public function viewElement($item): array { $settings = $this->getSettings(); $text = preg_replace($settings['regexp'], $settings['template'], $item->value); if (in_array($this->fieldDefinition->getType(), ['text', 'text_long', 'text_with_summary'])) { return [ '#type' => 'processed_text', '#text' => $text, '#format' => $item->format, '#langcode' => $item->getLangcode(), ]; } return [ '#markup' => $text, ]; } }