protected function BgImgFieldFormatter::buildElement in Background Image Field 8
Build the inline css style based on a set of files and a selector.
Parameters
array $files: An array of image files.
\Drupal\Core\Entity\EntityInterface $entity: The parent entity the field belongs to. Used for token replacement in the selector.
Return value
array Returns the built image with the prepared css in the html_head of render array
1 call to BgImgFieldFormatter::buildElement()
- BgImgFieldFormatter::viewElements in src/
Plugin/ Field/ FieldFormatter/ BgImgFieldFormatter.php - Builds a renderable array for a field value.
File
- src/
Plugin/ Field/ FieldFormatter/ BgImgFieldFormatter.php, line 190
Class
- BgImgFieldFormatter
- Plugin implementation of the 'image' formatter.
Namespace
Drupal\bg_img_field\Plugin\Field\FieldFormatterCode
protected function buildElement(array $files, EntityInterface $entity) {
$elements = [];
$css = "";
$image_link_setting = $this
->getSetting('image_link');
$cache_contexts = [];
if ($image_link_setting == 'file') {
$cache_contexts[] = 'url.site';
}
// Collect cache tags to be added for each item in the field.
$responsive_image_style = $this->responsiveImageStyleStorage
->load($this
->getSetting('responsive_image_style'));
$image_styles_to_load = [];
$cache_tags = [];
if ($responsive_image_style) {
$cache_tags = Cache::mergeTags($cache_tags, $responsive_image_style
->getCacheTags());
$image_styles_to_load = $responsive_image_style
->getImageStyleIds();
}
// Get image styles.
$image_styles = $this->imageStyleStorage
->loadMultiple($image_styles_to_load);
foreach ($image_styles as $image_style) {
$cache_tags = Cache::mergeTags($cache_tags, $image_style
->getCacheTags());
}
// Process the files to get the css markup.
foreach ($files as $file) {
$selector = $file['item']['css_selector'];
$selector = \Drupal::token()
->replace($selector, [
$entity
->getEntityTypeId() => $entity,
], [
'clear' => TRUE,
]);
$css .= $this
->generateBackgroundCss($file['file'], $responsive_image_style, $selector, $file['item']);
// Attach to head on element to create style tag in the html head.
if (!empty($css)) {
$current_path = \Drupal::request()
->getRequestUri();
if (preg_match('/node\\/(\\d+)\\/layout/', $current_path, $matches)) {
$elements = [
'#theme' => 'background_style',
'#css' => $css,
'#cache' => [
'tags' => $cache_tags,
'contexts' => $cache_contexts,
],
];
}
else {
// Use the selector in the id to avoid collisions with multiple
// background formatters on the same page.
$id = 'picture-background-formatter-' . $selector;
$elements['#attached']['html_head'][] = [
[
'#tag' => 'style',
'#value' => new CSSSnippet($css),
'#cache' => [
'tags' => $cache_tags,
'contexts' => $cache_contexts,
],
],
$id,
];
}
}
}
return $elements;
}