doublesecretagency / craft-starratings

Star Ratings plugin for Craft CMS
Other
4 stars 3 forks source link

[FR] Add total votes to Average Star Rating field type #17

Open johndwells opened 3 years ago

johndwells commented 3 years ago

A client request has come in to be able to see not just the average star rating for an entry, but also the total votes cast. The request specifically is to see these on the element listings pages.

The "Average Star Rating" field type, when used, renders the "locked stars" format using font awesome; I don't know if there's a "clean" way to add total votes to this UI; one perhaps simple route would be to provide an alternate view for the field, to render not as locked stars but as simple text info: avg rating & total votes.

... Perhaps the field type could be configured to show one or the other or both formats. Because tbh the locked stars are "good enough" for a front-end render, but for the client/editor it would perhaps be slightly more informative to report exact figures. Though the locked stars are a nice visual affirmation and would demonstrate what front-end users would see.

Of course in Craft 3.6 we're able to use custom templates as field types to report this fine-grained detail, but (currently) these are not displayed on the element listing pages. Hence this pesky FR. :)

Thanks!

lindseydiloreto commented 3 years ago

Hi John, thanks for the suggestion! This aligns with some long-term plans... I've made a few notes, and we can keep this FR open until it is eventually addressed. 👍

In the meantime, try adding this to your site's module (assuming you already have a module installed)...

use craft\base\Element;
use craft\elements\Entry;
use craft\events\RegisterElementTableAttributesEvent;
use craft\events\SetElementTableAttributeHtmlEvent;
use doublesecretagency\starratings\StarRatings;
use yii\base\Event;

// Add index table attributes
Event::on(
    Entry::class,
    Element::EVENT_REGISTER_TABLE_ATTRIBUTES,
    static function(RegisterElementTableAttributesEvent $event) {

        $event->tableAttributes['totalRatings'] = ['label' => 'Total'];

    }
);

// Modify index table display values
Event::on(
    Entry::class,
    Element::EVENT_SET_TABLE_ATTRIBUTE_HTML,
    static function(SetElementTableAttributeHtmlEvent $event) {

        /** @var Entry $entry */
        $entry = $event->sender;

        if ('totalRatings' === $event->attribute) {
            $event->html = StarRatings::$plugin->starRatings_query->totalVotes($entry->id);
        }

    }
);

This will add a new "Total" column to your Entry index page in the CP. Simply add that column and position it wherever you want.

totals@2x

Hope that helps!

johndwells commented 3 years ago

Thanks @lindseydiloreto that's super helpful! :)