public function ViewsFieldFormatter::viewElements in Views field formatter 8
Same name and namespace in other branches
- 8.2 src/Plugin/Field/FieldFormatter/ViewsFieldFormatter.php \Drupal\views_field_formatter\Plugin\Field\FieldFormatter\ViewsFieldFormatter::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/ ViewsFieldFormatter.php, line 251
Class
- ViewsFieldFormatter
- Class ViewsFieldFormatter.
Namespace
Drupal\views_field_formatter\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$settings = $this
->getSettings();
$cardinality = $items
->getFieldDefinition()
->getFieldStorageDefinition()
->getCardinality();
if (isset($settings['view']) && !empty($settings['view']) && \mb_strpos($settings['view'], '::') !== FALSE) {
list($view_id, $view_display) = \explode('::', $settings['view'], 2);
}
else {
return $elements;
}
$arguments = $this
->getArguments($items, $items[0], 0);
// If empty views are hidden, execute view to count result.
if (!empty($settings['hide_empty'])) {
$view = Views::getView($view_id);
if (!$view || !$view
->access($view_display)) {
return $elements;
}
// We try to reproduce the arguments which will be used below. We cannot
// just use $this->getArguments($items, $items[0], 0) as this might return
// items, which for example no longer exist, still you want to show the
// view when there are more possible entries.
if ((bool) $settings['multiple'] === TRUE && $cardinality !== 1) {
if (!empty($settings['implode_character'])) {
$arguments = $this
->getArguments($items, NULL, 0);
}
}
$view
->setArguments($arguments);
$view
->setDisplay($view_display);
$view
->preExecute();
$view
->execute();
if (empty($view->result)) {
return $elements;
}
}
$elements = [
'#cache' => [
'max-age' => 0,
],
[
'#type' => 'view',
'#name' => $view_id,
'#display_id' => $view_display,
'#arguments' => $arguments,
],
];
if ($cardinality !== 1 && (bool) $settings['multiple'] === TRUE) {
if (empty($settings['implode_character'])) {
foreach ($items as $delta => $item) {
$elements[$delta] = [
'#type' => 'view',
'#name' => $view_id,
'#display_id' => $view_display,
'#arguments' => $this
->getArguments($items, $items[$delta], $delta),
];
}
}
}
return $elements;
}