public function TextWithTitleAccordionFormatter::viewElements in Text with Title Field 8
Define how the field type is displayed.
Inside this method we can customize how the field is displayed inside pages.
Overrides FormatterInterface::viewElements
1 call to TextWithTitleAccordionFormatter::viewElements()
- TextWithTitleAccordionFormatter::view in src/
Plugin/ Field/ FieldFormatter/ TextWithTitleAccordionFormatter.php - Overide the view method so we can wrap the result in the accordion markup.
File
- src/
Plugin/ Field/ FieldFormatter/ TextWithTitleAccordionFormatter.php, line 54
Class
- TextWithTitleAccordionFormatter
- Plugin implementation of the 'TextWithTitleAccordionFormatter' formatter.
Namespace
Drupal\text_with_title\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
// Generate a unique ID for this item.
$id = $this->accordion_group_id . '--accordion-' . $delta;
$description_attributes = [];
// Body attributes.
$body_attributes = [
'id' => $id,
];
// Heading attributes.
$heading_attributes = [
'data-toggle' => 'collapse',
];
if ($this
->getSetting('only_one_open')) {
// Parent id.
$entity = $items
->getEntity();
$parent_id = $entity
->getEntityTypeId() . '_' . $entity
->bundle() . '_' . $entity
->id();
$heading_attributes['data-parent'] = '#' . $parent_id;
}
$attributes = [];
$elements[$delta] = [
'#theme' => 'text_with_title_panel',
'#heading' => [
'#plain_text' => $item->title,
],
'#heading_attributes' => new Attribute($heading_attributes),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#attributes' => new Attribute($attributes),
'#id' => $id,
'#target' => '#' . $id,
'#description' => [
'attributes' => new Attribute($description_attributes),
'content' => '',
'position' => 'before',
],
'#body' => [
'#type' => 'processed_text',
'#text' => $item->text['value'],
'#format' => $item->text['format'],
'#langcode' => $langcode,
],
'#body_attributes' => new Attribute($body_attributes),
];
}
return $elements;
}