Skip to content
jdorn edited this page Jul 18, 2012 · 3 revisions

This is a short tutorial on creating your own Report Filter.

We will create a StarRatingFilter that converts a numeric column (1-10) into that many images of stars.

The filter will take two options, 'on' and 'off'. For example, an 8/10 would mean the first 8 stars would be the 'on' image and the last 2 would be the 'off' image.

The Filter Class

Create a file classes/local/StarRatingFilter.php

<?php
class StarRatingFilter extends FilterBase {
	//a gold filled star
	public static $default_on = "<span style='color:gold; font-weight:bold;'>&#x272E;</span>";
	//a gray outlined star
	public static $default_off = "<span style='color:#ccc; font-weight:bold;'>&#x2729;</span>";

	public static function filter($value, $options = array(), $report = null) {
		//set defaults
		if(!isset($options['on'])) $options['on'] = self::$default_on;
		if(!isset($options['off'])) $options['off'] = self::$default_off;
		
		//get the value for the cell
		$number = intval($value->getValue());
		
		//make sure the value is between 0 and 10
		if($number < 0) $number = 0;
		elseif($number > 10) $number = 10;

		//build the html string
		$html = str_repeat($options['on'], $number) . str_repeat($options['off'], 10-$number);
		$html = "<span title='$number/10 stars' style='cursor:default;'>$html</span>";

		//set the new value
		//the second parameter (true) sets the value to an HTML string vs just a regular text string.
		$value->setValue($html, true);

		return $value;
	}
}

Testing it out

Next, we'll create a report to test the filter. To make things simple, we'll use a PHP report, but you can just as easily use MySql or MongoDB instead.

Create a file sample_reports/test/star_rating.php

<?php
//Testing Star Rating Filter
//FILTER: { filter: "StarRating", column: "Rating" }

$rows = array(
	array(
		'Name'=>'City of God',
		'Year'=>'2002',
		'Rating'=>'10'
	),
	array(
		'Name'=>'The Great Escape',
		'Year'=>'1963',
		'Rating'=>'9'
	),
	array(
		'Name'=>'Dune',
		'Year'=>'1984',
		'Rating'=>'6'
	),
	array(
		'Name'=>'Superbabies: Baby Geniuses 2',
		'Year'=>'2004',
		'Rating'=>'1'
	)
);

echo json_encode($rows);

View this report in your browser at http://localhost/report/html/?report=test/star_rating.php

To pass in your own 'on' and 'off' values, change the Filter header as follows:

FILTER: { filter: "StarRating", column: "Rating", params: {on: "X", off: ""}}

Refresh the report to see the changes.