I'm writing a module that contains a star field. Now I'm placing the stars using the viewElements function of my field formatter. Everything is working. But I need to place some syling to the field output. Can I send some css styling to the active theme using my module?

My field formatter looks like:

public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta => $item) {
    $total = $item->rating/2;

    $stars = '';

    //Place colored stars
    for($i =0; $i < floor($total); $i++)
    {
        $stars .= '<span class="star on"></span>';
    }

    //Place half star
    if(floor($total) != $total)
    {
       $stars .= '<span class="star half"></span>';
    }

    //Place open stars
    for($i = ceil($total); $i < 5; $i++)
    {
        $stars .= '<span class="star"></span>';
    }

      $element[$delta] = array(
        '#markup' => $stars,
      );
    }
    return $element;
  }

The only thing that I'm missing is the css style that looks like:

.star {
    font-size: x-large;
    width: 50px;
    display: inline-block;
    color: gray;
}
.star:last-child {
    margin-right: 0;
}
.star:before {
    content:'\2605';
}
.star.on {
    color: gold;
}
.star.half:after {
    content:'\2605';
    color: gold;
    position: absolute;
    margin-left: -20px;
    width: 10px;
    overflow: hidden;
}
  • Not directly related to your question, but you should not be using the t() function around the code you are using. The t() function should only ever be wrapped around strings, not variables. – Jaypan Dec 31 '16 at 13:18
  • Indeed I changed my code so that it will not call t(). – JimmyD Dec 31 '16 at 13:21
up vote 5 down vote accepted

To do this, you need to create a *.libraries.yml file, with the path to your css file in it:

MODULE.libaries.yml:

star-field:
  version: Version
  css:
    theme:
      path/to/stylesheet.css: {}

Then you can attach that library to your element:

$element['#attached']['library'][] = MODULE/star-field;

This can be overridden in a theme if/when necessary, so this styling should be considered the default styling that the module creates.

More reading: https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.