Tips, tricks, articles, rankings for Drupal developers

Getting percentage rating without using Drupal tokens

damaya's picture
damaya | Thu, 24/04/2014 - 14:13

Sometimes when we add a field into a view in Drupal, is useful to use the tokens that the field provides.

In particular, Fivestar module has a field named 'rating' with an interesting tokens such as:

 

[field_rating-rating] == Raw rating

[field_rating-target] == Raw target

 

However, in some cases the value returned by these tokens will not be expected. In these cases we can use a field of PHP and take rating values ​​separately and then calculate the average with a simple formula.

 

An example for this could be the following code: 

 

$stars = $data->field_field_rating[0]['rendered']['user']['#instance_settings']['stars'];

$avg_rating = $data->field_field_rating[0]['rendered']['user']['#item']['average'];
echo ($stars * $avg_rating) / 100;
 
With $stars variable, we will obtain the number of stars of the field; on the other hand, $avg_rating provides the 'target' value (divisor number). Last step will be operate with these variables and return as percentage.
Rating: 
0
No votes yet
Token category: 
Drupal version: 
Drupal skill: 
Dependencies: 
PHP, Fivestar