public function FieldTokenValueTextFormatter::viewElements in Field Token Value 2.x
Same name and namespace in other branches
- 8 src/Plugin/Field/FieldFormatter/FieldTokenValueTextFormatter.php \Drupal\field_token_value\Plugin\Field\FieldFormatter\FieldTokenValueTextFormatter::viewElements()
Builds a renderable array for a field value.
Parameters
\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.
string $langcode: The language that should be used to render the field.
Return value
array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.
Overrides FormatterInterface::viewElements
File
- src/
Plugin/ Field/ FieldFormatter/ FieldTokenValueTextFormatter.php, line 131
Class
- FieldTokenValueTextFormatter
- Provides the Field Token Value Text field formatter.
Namespace
Drupal\field_token_value\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
$selected = $this
->getSetting('wrapper');
$output_as_link = $this
->getSetting('link');
$entity = $items
->getEntity();
// Because the field value is determined by the instance settings, even if the
// user somehow managed to add multiple items, the same value will be set for
// each one. Because of this we only ever use the first value.
if (!empty($items[0])) {
$element[0] = [
'#type' => 'html_tag',
'#tag' => 'p',
'#value' => $items[0]->value,
];
// Update the output value based on the link setting
if ($output_as_link && !$entity
->isNew()) {
try {
$uri = $entity
->toUrl();
} catch (UndefinedLinkTemplateException $e) {
// This exception is thrown by \Drupal\Core\Entity\Entity::urlInfo()
// and it means that the entity type doesn't have a link template nor
// a valid "uri_callback", so don't bother trying to output a link for
// the rest of the referenced entities.
$output_as_link = FALSE;
}
}
if ($output_as_link && isset($uri) && !$entity
->isNew()) {
$link = Link::fromTextAndUrl($element[0]['#value'], $uri)
->toRenderable();
$element[0]['#value'] = render($link);
}
if (!empty($selected)) {
// Retrieve the wrapper info from the service.
$wrapper_info = $this->wrappers
->getDefinition($selected);
// Update the output tag based on the wrapper info.
$element[0]['#tag'] = $wrapper_info['tag'];
// If the wrapper contains attributes such as class, add them in.
if (isset($wrapper_info['attributes'])) {
$element[0]['#attributes'] = $wrapper_info['attributes'];
}
// Allow modules to alter the output of the field. For example to possibly
// attach CSS or JS for a particular tag.
\Drupal::moduleHandler()
->alter('field_token_value_output', $element[0], $wrapper_info);
}
}
return $element;
}