json_table-1.0.6/src/Plugin/Field/FieldFormatter/JsonFormatter.php
src/Plugin/Field/FieldFormatter/JsonFormatter.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;
/**
* Plugin implementation of the 'json_formatter' formatter.
*/
#[FieldFormatter(
id: 'json_formatter',
label: new TranslatableMarkup('Json view'),
field_types: [
'json',
],
)]
class JsonFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'modes' => [
'collapse' => TRUE,
'nl2br' => FALSE,
'recursive_collapser' => FALSE,
'escape' => FALSE,
'strict' => FALSE,
],
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$form['modes'] = [
'#title' => $this->t('Mode'),
'#type' => 'checkboxes',
'#options' => [
'collapse' => $this->t('Collapse all nodes when rendering first time'),
'nl2br' => $this->t('Convert new line to') . '<br>',
'recursive_collapser' => $this->t('Collapse nodes recursively'),
'escape' => $this->t('Escape HTML in key'),
'strict' => $this->t('In strict mode, invalid JSON value type will throw a error'),
],
'#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 = [];
$modeDefault = self::defaultSettings()['modes'];
if (!empty($mode = $this->getSetting('modes'))) {
$summaryOption = [];
if (is_string($mode)) {
$mode = $modeDefault;
}
foreach ($mode as $name => $value) {
if ($value) {
$summaryOption[] = $name;
}
}
$summary['mode'] = $this->t('Mode: @mode', ['@mode' => implode(', ', $summaryOption)]);
}
return $summary;
}
/**
* {@inheritDoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$field_name = $items->getName();
$settings = array_diff($this->getSetting('modes'), [0]);
$settings = array_fill_keys($settings, TRUE);
$elements = !empty($items) ? [
'#attached' => [
'library' => ['json_table/jquery_jsonview'],
'drupalSettings' => [
'json_view' => [$field_name => $settings],
],
],
] : [];
foreach ($items as $delta => $item) {
$elements[$delta] = [
'#type' => 'html_tag',
'#tag' => 'pre',
'#value' => $item->value,
'#langcode' => $langcode,
'#attributes' => [
'data-json-field' => $field_name,
'class' => ['json-view'],
],
];
}
return $elements;
}
}
