$49

Upvote

Documentation  •  Changelog

Documentation

Events

Upvote events follow the same pattern as standard Craft events.

There are two events which are raised when a new vote is cast...

use doublesecretagency\upvote\Upvote;
use doublesecretagency\upvote\events\VoteEvent;
use yii\base\Event;

// Do something BEFORE a vote is cast...
Event::on(Upvote::class, Upvote::EVENT_BEFORE_VOTE, function(VoteEvent $event) {
    // See the complete list of parameters below
    $elementId = $event->id;
});

// Do something AFTER a vote is cast...
Event::on(Upvote::class, Upvote::EVENT_AFTER_VOTE, function(VoteEvent $event) {
    // See the complete list of parameters below
    $elementId = $event->id;
});

There are also two events which are raised then a vote is removed (or swapped)...

use doublesecretagency\upvote\Upvote;
use doublesecretagency\upvote\events\VoteEvent;
use yii\base\Event;

// Do something BEFORE a vote is removed...
Event::on(Upvote::class, Upvote::EVENT_BEFORE_UNVOTE, function(VoteEvent $event) {
    // See the complete list of parameters below
    $elementId = $event->id;
});

// Do something AFTER a vote is removed...
Event::on(Upvote::class, Upvote::EVENT_AFTER_UNVOTE, function(VoteEvent $event) {
    // See the complete list of parameters below
    $elementId = $event->id;
});

When are events triggered?

When a user casts an upvote or downvote, a "vote" event is triggered.

When a user removes an existing vote, an "unvote" event is triggered (aka "antivote").

When a user switches to the opposing vote, it will "unvote" the original before casting a new "vote".

All events provide the same set of parameters:

Param Type Description
id int Element ID of the element being voted on.
key string or null Optional key for allowing multiple vote types.
itemKey string Combination of `id` and optional `key`.
userId int ID of the user casting a vote (if login is required to vote).
userVote int (1 or -1) The user's vote. Positive one is an upvote, negative one is a downvote.
isAntivote bool Was the event triggered by a vote removal?
tally int The combined value of all votes. (Upvotes - Downvotes)
totalVotes int The combined total number of votes. (Upvotes + Downvotes)
totalUpvotes int The total number of Upvotes cast.
totalDownvotes int The total number of Downvotes cast.

Minor changes in Upvote 2.1

The parameters of each event have been adjusted slightly in v2.1.

Determine vote removal

You can check whether the vote was a removal (aka "unvote") by checking the isAntivote value. If true, the vote is an antivote, which means two things...

  • isAntivote will be true. It will be false when a normal vote is cast.
  • userVote will have a value that is the exact opposite of the vote which was removed. So if the original vote was a (1), the antivote will be (-1).