Thursday, April 16, 2009

APEX Star Rating - Amazon style

Recently there were two threads on the APEX OTN Forum regarding the implementation of an Amazon-style star rating mechanism (this thread and this thread).
Using this jQuery plug-in that implementation is not so difficult. The first step (of course you've installed jQuery) is to install the JavaScript and CSS of the plug-in. To create a demo I added two columns to the DEMO_PRODUCT_INFO table : RATING and VOTES.
The second step is to create a PL/SQL function and use that in your select statement to show the current rating:

create or replace function GET_STARS
( pID in NUMBER
, pRating in NUMBER
) return VARCHAR2
is
l_retval varchar2(2000) :='';
BEGIN
FOR i in 1..5 LOOP
IF i = pRating
THEN l_retval := l_retval ||'<input class="star" id="'||pID||'" name="star'||pID||'" value="'||i||'" checked="checked" type="radio">';
ELSE l_retval := l_retval ||'<input class="star" id="'||pID||'" name="star'||pID||'" value="'||i||'" type="radio">';
END IF;
END LOOP;
RETURN l_retval;
END;
Then add a click event to the elements with a 'star' class
$(function(){
$('.star').click(function() {
saveRating( $(this).attr("id"), $(this).children().attr("title") );
votes = Number($(this).parent().parent().next().html()) + 1;
$(this).parent().parent().next().html( votes );
});
});
where saveRating is just a 'regular' AJAX OnDemand process that calls a PL/SQL Procedure that does the actual update.
The result is quite good: You can hover over the stars and a click saves the rating (of course you would need another data model to save and calculate all ratings and prevent users from rating more than once, but that's for later).
You can see it live on apex.oracle.com.
Post a Comment