public function JwplayerFormatter::viewElements in JW Player 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/ JwplayerFormatter.php, line 189
Class
- JwplayerFormatter
- Plugin implementation of the 'foo_formatter' formatter.
Namespace
Drupal\jw_player\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = array();
$settings = $this
->getSettings();
// Prepare preview image.
$image_style = NULL;
$image_url = NULL;
$cache_tags = [];
if ($settings['preview_image_field']) {
$split = explode('|', $settings['preview_image_field']);
$preview_image_field = $split[1];
if ($preview_items = $items
->getEntity()
->get($preview_image_field)) {
if ($image_style = ImageStyle::load($settings['preview_image_style'])) {
if ($image = $items
->getEntity()->{$preview_image_field}->entity) {
$image_url = $image_style
->buildUrl($image
->getFileUri());
$cache_tags = $image_style
->getCacheTags();
}
}
}
}
// Process files for the theme function.
foreach ($items as $delta => $item) {
if ($item->entity) {
$file_uri = $item->entity
->getFileUri();
$file_mime = $item->entity
->getMimeType();
$uri = file_create_url($file_uri);
// Add cache tags for the referenced file and the preset if it can be
// loaded, to prevent fatal errors.
$tags = Cache::mergeTags($cache_tags, $item->entity
->getCacheTags());
}
elseif ($this->fieldDefinition
->getType() === 'link') {
$uri = $item->uri;
$file_mime = FALSE;
$tags = [];
}
else {
continue;
}
if ($preset = $this
->loadPreset()) {
$tags = Cache::mergeTags($tags, $preset
->getCacheTags());
}
$element[$delta] = [
'player' => [
'#type' => 'jw_player',
'#file' => $item->entity,
'#file_url' => $uri,
'#file_mime' => $file_mime,
'#item' => $item,
'#preset' => $this
->getSetting('jwplayer_preset'),
// Give each instance of the player a unique id. A random hash is
// used in place of drupal_html_id() due to potentially conflicting
// ids in cases where the entire output of the theme function is
// cached. Prefix with jwplayer, as ID's that start with a number
// are not valid.
'#html_id' => 'jwplayer-' . md5(rand()),
],
'#attached' => [
'library' => [
'jw_player/jwplayer',
],
],
'#cache' => [
'tags' => $tags,
],
];
// Add preview image.
if ($image_url) {
$element[$delta]['player']['#settings']['image'] = $image_url;
}
}
return $element;
}