public function ImagefieldSlideshowFieldFormatter::viewElements in Imagefield Slideshow 8
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/ ImagefieldSlideshowFieldFormatter.php, line 290
Class
- ImagefieldSlideshowFieldFormatter
- Plugin implementation of 'imagefield_slideshow_field_formatter' formatter.
Namespace
Drupal\imagefield_slideshow\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
// Get the Entity value as array.
$file = $items
->getEntity()
->toArray();
// Early opt-out if the field is empty.
$images = $this
->getEntitiesToView($items, $langcode);
if (empty($images)) {
return $elements;
}
$image_style_setting = $this
->getSetting('imagefield_slideshow_style');
$image_style = NULL;
if (!empty($image_style_setting)) {
$image_style = \Drupal::entityTypeManager()
->getStorage('image_style')
->load($image_style_setting);
}
$image_uri_values = [];
foreach ($images as $image) {
$image_uri = $image
->getFileUri();
// Get image style URL.
if ($image_style) {
$image_uri = ImageStyle::load($image_style
->getName())
->buildUrl($image_uri);
}
else {
// Get absolute path for original image.
$image_uri = $image
->createFileUrl(FALSE);
}
// Populate image uri's with fid.
$fid = $image
->toArray()['fid'][0]['value'];
$image_uri_values[$fid] = [
'uri' => $image_uri,
];
}
// Populate the title and alt of images based on fid.
foreach ([
'title',
'alt',
] as $element_name) {
$field_name = $this->fieldDefinition
->getName();
if (array_key_exists($field_name, $file)) {
foreach ($file[$field_name] as $key => $value) {
$image_uri_values[$value['target_id']]['alt'] = $value['alt'];
$image_uri_values[$value['target_id']]['title'] = $value['title'];
}
}
}
// Enable prev next if only more than one image.
$prev_next = $this
->getSetting('imagefield_slideshow_prev_next');
if (count($image_uri_values) <= 1) {
$prev_next = FALSE;
}
$elements[] = [
'#theme' => 'imagefield_slideshow',
'#url' => $image_uri_values,
'#prev_next' => $prev_next,
'#effect' => $this
->getSetting('imagefield_slideshow_style_effects'),
'#pause' => $this
->getSetting('imagefield_slideshow_style_pause'),
'#speed' => $this
->getSetting('imagefield_slideshow_transition_speed'),
'#timeout' => $this
->getSetting('imagefield_slideshow_timeout'),
'#pager' => $this
->getSetting('imagefield_slideshow_pager'),
];
// Attach the image field slide show library.
$elements['#attached']['library'][] = 'imagefield_slideshow/imagefield_slideshow';
// Not to cache this field formatter.
$elements['#cache']['max-age'] = 0;
return $elements;
}