datafield-1.x-dev/src/Plugin/DataField/FieldFormatter/StringFormatter.php
src/Plugin/DataField/FieldFormatter/StringFormatter.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: 'string',
label: new TranslatableMarkup('Plain text'),
field_types: ['string', 'uri', 'email', 'json', 'serial'],
)]
class StringFormatter implements DataFieldFormatterInterface {
use StringTranslationTrait;
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
$options['link_to_entity'] = FALSE;
return $options;
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
return [];
}
/**
* {@inheritdoc}
*/
public function settingsSummary($settings = []) {
$summary = [];
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements($item, $langcode) {
$url = NULL;
$entity = $item->entity;
if (empty($item->value)) {
return $item->value;
}
$entity_type = $entity->getEntityType();
if (!empty($item->settings['link_to_entity']) && !$entity->isNew() && $entity_type->hasLinkTemplate('canonical')) {
$url = $this->getEntityUrl($entity);
}
$view_value = $this->viewValue($item->value);
if ($url) {
return [
'#type' => 'link',
'#title' => $view_value,
'#url' => $url,
];
}
else {
return $view_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);
}
}
