public function CshsGroupByRootFormatter::viewElements in Client-side Hierarchical Select 8.3
Same name and namespace in other branches
- 8 src/Plugin/Field/FieldFormatter/CshsGroupByRootFormatter.php \Drupal\cshs\Plugin\Field\FieldFormatter\CshsGroupByRootFormatter::viewElements()
- 8.2 src/Plugin/Field/FieldFormatter/CshsGroupByRootFormatter.php \Drupal\cshs\Plugin\Field\FieldFormatter\CshsGroupByRootFormatter::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/ CshsGroupByRootFormatter.php, line 155
Class
- CshsGroupByRootFormatter
- Plugin implementation of the "Group by root" formatter.
Namespace
Drupal\cshs\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) : array {
$depth = $this
->getSetting('depth');
$linked = $this
->getSetting('linked');
$reverse = $this
->getSetting('reverse');
$elements = [];
foreach ($this
->getEntitiesToView($items, $langcode) as $term) {
$tree = $this
->getTermParents($term, !$reverse);
if ($depth > 0) {
// @todo This is not an optimal solution as we may load lots of entities that won't be used.
$tree = \array_slice($tree, 0, $depth, TRUE);
}
$labels = $this
->getTermsLabels($tree, $linked);
$root = \array_shift($tree);
$root_id = $root
->id();
$root_label = \array_shift($labels);
if (!isset($elements[$root_id])) {
$elements[$root_id] = [
'#theme' => 'cshs_term_group',
'#id' => $root_id,
'#title' => $root_label,
'#terms' => [],
];
}
// Replace calls to `\array_merge()` and `\array_unique()` by the loop.
foreach ($labels as $i => $label) {
$unique_key = (string) $tree[$i]
->label();
if (!isset($elements[$root_id]['#terms'][$unique_key])) {
$elements[$root_id]['#terms'][$unique_key] = [
'id' => $tree[$i]
->id(),
'label' => $label,
'parent' => $tree[$i]->parent->target_id,
];
}
}
}
if ($sort_function = static::SORT_FUNCTIONS[$this
->getSetting('sort')] ?? NULL) {
foreach ($elements as $root_id => $element) {
$sort_function($elements[$root_id]['#terms']);
}
}
return $elements;
}