json_table-1.0.6/src/Plugin/Field/FieldFormatter/JsonRawFormatter.php

src/Plugin/Field/FieldFormatter/JsonRawFormatter.php
<?php

namespace Drupal\json_table\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\Yaml\Yaml;

/**
 * Plugin implementation of the 'json_string_formatter' formatter.
 */
#[FieldFormatter(
  id: 'json_raw_formatter',
  label: new TranslatableMarkup('Json raw'),
  field_types: [
    'json',
  ],
)]
class JsonRawFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'modes' => 'json',
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form['modes'] = [
      '#title' => $this->t('Mode'),
      '#type' => 'select',
      '#options' => [
        'json' => $this->t('Json formatter'),
        'yaml' => $this->t('Yaml'),
      ],
      '#default_value' => $this->getSetting('modes'),
    ];
    // Needed to avoid errors notified as log message.
    if (isset($form['#after_build'])) {
      $form['#after_build'] = NULL;
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = [];
    if (!empty($mode = $this->getSetting('modes')) && is_string($mode)) {
      $summary['mode'] = $this->t('Mode: @mode', ['@mode' => $mode]);
    }
    return $summary;
  }

  /**
   * {@inheritDoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];
    $isYaml = $this->getSetting('modes') == 'yaml';
    foreach ($items as $delta => $item) {
      $value = $item->value;
      if ($isYaml) {
        $data = json_decode($value, TRUE);
        $value = Yaml::dump($data);
        $element[$delta] = [
          '#type' => 'html_tag',
          '#tag' => 'pre',
          '#value' => $value,
          '#langcode' => $langcode,
        ];
      }
      else {
        // Render each element as markup.
        $element[$delta] = ['#markup' => $value];
      }
    }
    return $element;
  }

}

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

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