Star Rating

Posts on a project page such as this one are sorted in ascending chronological order.


Project: Star Rating
Tags: Drupal 7, Theming

One of my clients needs a star rating system for his product reviews. There is an old module for that: FiveStar. And that's fine because he's still running Drupal 7. But he has expressed ambitions to migrate to Drupal 8 and the latest version of FiveStar for Drupal 8 is still in alpha.

The easy solution would be not to worry and install one more module on his website. But wait a minute, in the module admin page Module Filter says: «311 of 593». Yikes! Also, FiveStar was created 14 years ago for solving a specific use case: letting members of a community rate content while browsing a website (i.e. when content is displayed in Default/Full content view mode).

In the present use case, a customer is invited to edit a node linked to the product he recently purchased. That's a much simpler use case, one that does not require a very sophisticated UI, in a node edit form, a simple select with options 1 to 5 stars will do just fine. Where we want this system to shine is in how it displays the rating, not in how it lets users set the rating.

Finally, if a simple and static home-made system can be produced then migrating it to Drupal 8 will be trivial.

Project: Star Rating
Tags: Drupal 7, Theming

Initial solution to display the star rating is based on a How To:

  • in the Review node, create field_review_rating of type Integer and add the star options
  • the custom HTML markup for this field is provided by theme_preprocess_field() in template.php
  • create/add field--field-review-rating.tpl.php to the theme's template folder and use the custom HTML markup to override its display
  • Font Awesome Icon Library is loaded in html.tpl.php
  • add the CSS to color the stars in the theme's CSS folder

This works fine when a node is displayed. But what about a list of reviews produced by Views?

How can I reproduce the node's custom display in a Views' display? It's definitely possible but it quickly gets more complicated. It also means that our system will have 2 templates to handle these 2 separate contexts, duplication is rarely ideal and often leads to more work and errors...

AH! a better solution would be to use a content view mode e.g. Teaser instead of fields, that way there is no need to work with Views' templates + the work done in field--field-review-rating.tpl.php 100% recyclable :)

Project: Star Rating
Tags: Drupal 7, Theming

Last steps:

  • transpose the re-rewriting I attempted to do in Views' fields into a new node--review--teaser.tpl.php
  • update theme_preprocess_node() in template.php to add theme hook suggestion for the Teaser view mode; otherwise node--review.tpl.php is always used

That's it. This is a good example where view modes make your life easier.

After deploying this home-made Star Rating system, the client had only this to say: «Looks perfect!»