Custom Voting API Calculation

The Voting API is really nice when used in conjunction with a module like Fivestar. It takes all of the complexity out of setting up a voting/rating system. On occasion, however, you need it to do some things that aren’t built in. Using the VotingAPI’s API, I’ll show you how to trigger a function (send an email, write a message to the screen, etc.) when a piece of content receives a fifth vote of four stars or greater. That is, a node may have four votes of five stars, and two votes of two stars. As soon as the next greater-than-four vote goes in, we want to do something about it. In our case, the client wants to receive an email when a node is popular, and has had five four-star-or-greater votes.

That’s enough explaining. Let’s get started! First of all, please do not rely on the examples here as they are outdated! Search for “votingapi” in the Drupal APIfor the latest docs.

The code is pretty straightforward (if you understand SQL and PHP arrays). The main point of confusion for me while writing this function was the line that actually writes to the $results variable.

I was trying to use $cache instead of $results as I’d seen this documented a few different ways… even the example in the documentation seems to have it wrong!

I’ve included some screenshots below to show you what the VotingAPI cache table looks like after adding our custom calculation. The thumbnails are tiny, just below the code.

If you are unsure how to use this code, or where to put it?   Perhaps you need to look at Creating a Custom Module.

 

Tagged with: , , , , , ,
Posted in Development

Leave a Reply

Your email address will not be published. Required fields are marked *

*