Hi,
When I select "Write background-image to CSS selector", it will not output image to css selector.
Inline style attr working great!

Comments

joonapenttila created an issue. See original summary.

niekheezemans’s picture

Hi,

I am experiencing the same thing. I created a fix by only adding the '_$id' when using the inline styling option and adding the rendering.
In the BackgroundImageFormatter.php file on line 143 I modified the code like this:

$selector = strip_tags($this->getSetting('background_image_selector'));
// Only add an id when using inline styles
if( $this->getSetting('background_image_output_type') == 'inline' ){
   $selector .= '_' . $id;
}

Also the styling is not rendered in the switch statement case 'css'. Add this line just before the break:

case 'css':
          $data = [
            '#tag' => 'style',
            '#value' => $this->generateCssString($theme),
          ];

          $elements['#attached']['html_head'][] = [
            $data,
            'background_image_formatter_' . $id,
          ];
          // This line renders the style elements to the HTML file
          \Drupal::service('renderer')->render($elements);
          break;

When you use a selector make sure you use a '.' for a class or '#' for an id. F.e `.image-bg or `#image-bg`

Grtz Niek

The complete BackgroundImageFormatter.php file:

<?php /**
 * @file
 * Contains \Drupal\background_image_formatter\Plugin\Field\FieldFormatter\BackgroundImageFormatter.
 */

namespace Drupal\background_image_formatter\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\image\Entity\ImageStyle;
use Drupal\image\Plugin\Field\FieldFormatter\ImageFormatter;

/**
 * Plugin implementation of the background_image_formatter.
 *
 * @FieldFormatter(
 *  id = "background_image_formatter",
 *  label = @Translation("Background Image"),
 *  field_types = {"image"}
 * )
 */
class BackgroundImageFormatter extends ImageFormatter {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'image_style' => '',
      'background_image_output_type' => 'inline',
      'background_image_selector' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {

    $element = [];

    $image_styles = image_style_options(FALSE);

    $element['image_style'] = [
      '#title' => t('Image style'),
      '#type' => 'select',
      '#options' => $image_styles,
      '#default_value' => $this->getSetting('image_style'),
      '#empty_option' => t('None (original image)'),
      '#description' => t('Select the image style to use.'),
    ];

    $element['background_image_output_type'] = [
      '#title' => t('Output To'),
      '#type' => 'select',
      '#options' => [
        'inline' => t('Write background-image to inline style attribute'),
        'css' => t('Write background-image to CSS selector'),
      ],
      '#default_value' => $this->getSetting('background_image_output_type'),
      '#required' => TRUE,
      '#description' => t('Define how background-image will be printed to the dom.'),
    ];

    $element['background_image_selector'] = [
      '#title' => t('CSS Selector'),
      '#type' => 'textfield',
      '#default_value' => $this->getSetting('background_image_selector'),
      '#required' => FALSE,
      '#description' => t('CSS selector that image(s) are attached to.'),
    ];

    return $element;

  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {

    $summary = array();

    $image_styles = image_style_options(FALSE);

    unset($image_styles['']);

    $select_style = $this->getSetting('image_style');

    if (isset($image_styles[$select_style])) {
      $summary[] = t('URL for image style: @style', ['@style' => $image_styles[$select_style]]);
    }
    else {
      $summary[] = t('Original image');
    }

    $summary[] = t('Output type: @output_type', ['@output_type' => $this->getSetting('background_image_output_type')]);


    $summary[] = t('The CSS selector <code>@background_image_selector

will be created with the image set to the background-image property.', [
'@background_image_selector' => $this->getSetting('background_image_selector') . '_id',
]);

return $summary;
}

/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {

$elements = [];

$image_style = NULL;

if (!$this->isBackgroundImageDisplay()) {
return $elements;
}

$image_style = $this->getSetting('image_style');

if (!empty($image_style)) {
$image_style = ImageStyle::load($image_style);
}

foreach ($items as $delta => $item) {

if (!$item->entity) {
continue;
}

$image_uri = $item->entity->url();

$id = $item->entity->id();

if ($image_style) {
$image_uri = $item->entity->getFileUri();

$image_uri = ImageStyle::load($image_style->getName())->buildUrl($image_uri);
}

$selector = strip_tags($this->getSetting('background_image_selector'));
if( $this->getSetting('background_image_output_type') == 'inline' ){
$selector .= '_' . $id;
}

$theme = array(
'#background_image_selector' => $selector,
'#image_uri' => $image_uri,
);

switch ($this->getSetting('background_image_output_type')) {
case 'css':
$data = [
'#tag' => 'style',
'#value' => $this->generateCssString($theme),
];

$elements['#attached']['html_head'][] = [
$data,
'background_image_formatter_' . $id,
];

\Drupal::service('renderer')->render($elements);
break;

case 'inline':

$theme['#theme'] = 'background_image_formatter_inline';

$elements[$delta] = array(
'#markup' => \Drupal::service('renderer')->render($theme),
);

break;
}
}

return $elements;
}

protected function isBackgroundImageDisplay() {
return $this->getPluginId() == 'background_image_formatter';
}

protected function generateCssString($theme) {
return $theme['#background_image_selector'] . '{ background-image: url("' . $theme['#image_uri'] . '"); }';
}

}

garethhallnz’s picture

Hi guys, just checked one of my sites and it's working for me.

A few questions:
1. Have you entered a css class in the field UI?
2. What version of Drupal?
3. Is single of multi field?
4. Exact steps to reproduce or what expectation has not been met?

joonapenttila’s picture

Thanks niekheezemans! :)

alex_optim’s picture

Status: Active » Needs review
StatusFileSize
new737 bytes

Create patch.

niekheezemans’s picture

Thnx for creating the patch Alex, will do it next time.

@ garethhallnz:
1. Have you entered a css class in the field UI? => Yes
2. What version of Drupal? => Drupal 8.2.1
3. Is single of multi field? => What do you mean? I am using the CSS selector class once on a page...
4. Exact steps to reproduce or what expectation has not been met? => When using the option Background Image Format -> Output to: Write Background-image to CSS selector, the background image was not attached to the CSS selector since the module added an $id value to the css classname that is used for attaching the backgroun-image style. F.e. when you entered

.test-bg

as a selector, the module added an $id to the selector making the CSS selector f.e.

.test-bg_99
garethhallnz’s picture

Status: Needs review » Patch (to be ported)

Ohh I see. I think the current functionality is correct. The entityID must be added for when there is more than 1 image on the page.

For example
If you have and article content type with a full and teaser view mode showing a background image with the class of test
Now if you create a view showing recent articles with the teaser view mode; you need to append the entityID the make the selector unique.

I think the main thing that missing for the "Write Background-image to CSS selector" option is that it doesn't create an empty div for the css selector?

NOTE:
It's also worth mentioning this project has been marked as obsolete.

Therefor it's not worth doing any work here as we are in the process of merging this with Background Images Formatter module.

Progress to be document at: https://www.drupal.org/node/2820564

  • Zulljin committed 5fb4cc0 on 8.x-1.x authored by alex_optim
    Issue #2822280 by alex_optim: Write background-image to to CSS selector...

Zulljin credited Zulljin.

zulljin’s picture

Status: Patch (to be ported) » Fixed

alex_optim, thanks for the patch.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

alex_optim’s picture