public function FieldTokenValueTextFormatter::viewElements in Field Token Value 8
Same name and namespace in other branches
- 2.x 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 119
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');
// 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,
];
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;
}