Five Start Widget Formatter for List Integer Field for Drupal 8 using CSS only

You, DrupalDrupal field api
Back

First, create the field formatter for list integer field type. Add this file in your custom module.

<?php

namespace Drupal\CUSTOM_MODULE\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;

/**
 * Plugin implementation of the 'five_start_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "five_start_formatter",
 *   label = @Translation("Five Start Widget"),
 *   field_types = {
 *     "list_integer",
 *   }
 * )
 */
class FiveStartFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = [];
    $summary[] = $this->t('Displays the five start widget.');
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];
    foreach ($items as $delta => $item) {
      $highlighted_stars = str_repeat('<span class="active">☆</span>', (int)$item->value);
      $normal_stars = str_repeat('<span>☆</span>', 5 - (int)$item->value);
      $element[$delta] = ['#markup' => '<div class="rating">' . $highlighted_stars . $normal_stars . '</div>'];
    }
    return $element;
  }
}

Then CSS styles.

/\*
    Ratings Stars
    (with as little code as possible)
\*/
.rating {
  unicode-bidi: bidi-override;
  font-size: 2em
}
.rating > span {
  display: inline-block;
  position: relative;
  width: 1.1em;
}
.rating > span.active {
  color: transparent;
}
.rating > span.active:before {
   content: "\\2605";
   position: absolute;
   left: 0;
   color: gold;
}

Output

Five start widget

© Heshan Wanigasooriya.RSS

🍪 This site does not track you.