datafield-1.x-dev/src/Plugin/DataField/FieldFormatter/JsonFormatter.php
src/Plugin/DataField/FieldFormatter/JsonFormatter.php
<?php
namespace Drupal\datafield\Plugin\DataField\FieldFormatter;
use Drupal\Core\Entity\EntityInterface;
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 'string' formatter.
*/
#[FieldFormatter(
id: 'json',
label: new TranslatableMarkup('Json text'),
field_types: ['json'],
)]
class JsonFormatter implements DataFieldFormatterInterface {
use StringTranslationTrait;
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [];
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
return [];
}
/**
* {@inheritdoc}
*/
public function settingsSummary($settings = []) {
$summary = [];
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements($item, $langcode) {
if (is_null($item->value)) {
return $item->value;
}
$fieldName = $item->field_name . '-' . $item->machine_name;
if (empty($item->settings['hidden'])) {
return [
'#type' => 'html_tag',
'#tag' => 'pre',
'#value' => $item->value,
'#langcode' => $langcode,
'#attributes' => [
'data-json-field' => $fieldName,
'class' => ['json-view'],
],
'#attached' => [
'library' => ['datafield/jquery_jsonview'],
'drupalSettings' => [
'json_view' => [$fieldName => ['collapse' => TRUE]],
],
],
];
}
else {
return $this->viewValue($item->value);
}
}
/**
* {@inheritdoc}
*/
protected function viewValue($value) {
// The text value has no text format assigned to it, so the user input
// should equal the output, including newlines.
return [
'#type' => 'inline_template',
'#template' => '{{ value|nl2br }}',
'#context' => ['value' => $value],
];
}
/**
* Gets the URI elements of the entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity object.
*
* @return \Drupal\Core\Url
* The URI elements of the entity.
*/
protected function getEntityUrl(EntityInterface $entity) {
// For the default revision, the 'revision' link template falls back to
// 'canonical'.
// @see \Drupal\Core\Entity\Entity::toUrl()
$rel = $entity->getEntityType()->hasLinkTemplate('revision') ? 'revision' : 'canonical';
return $entity->toUrl($rel);
}
}
