Skip to content
jdorn edited this page Jul 18, 2012 · 1 revision

This is a short tutorial on creating a new Header to use in reports.

We will create a Limit filter that will only display a subset of rows in a report.

The filter will have 2 options, 'limit' and 'offset'.

The Header Class

First, create the Header Class. Create the file classes/local/LimitHeader.php

<?php
class LimitHeader extends HeaderBase {
	//only params listed here may be passed into the header
	//anything else will throw an error
	static $validation = array(
		'limit'=>array(
			'type'=>'number',
			'default'=>'10'
		),
		'offset'=>array(
			'type'=>'number',
			'default'=>'0'
		),
	);
	
	//this is called when the header is parsed
	public static function init($params, &$report) {
		//store the params in the report for use after the report is run
		$report->options['Limit'] = $params;
	}
	
	//provide an optional shortcut syntax
	public static function parseShortcut($value) {
		//the shortcut syntax "OFFSET, LIMIT"
		if(strpos($value, ',') !== false) {
			list($offset,$limit) = explode(',', $value, 2);
		}
		//the shortcut syntax "LIMIT"
		else {
			$limit = $value;
			$offset = 0;
		}
		
		$params = array(
			'limit'=>intval(trim($limit)),
			'offset'=>intval(trim($offset))
		);
		
		return $params;
	}
	
	//this is called after the report is run and all filters are applied
	//it is the last thing that is run before rendering the report to the screen
	public static function beforeRender(&$report) {
		//get the limit options from the report
		$limit = $report->options['Limit']['limit'];
		$offset = $report->options['Limit']['offset'];
		
		//array slice the report rows
		$report->options['Rows'] = array_slice($report->options['Rows'], $offset, $limit);
	}
}

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/limit_header.php

<?php
//Testing the Limit Header
//LIMIT: { limit: 2, offset: 1 }

$rows = array(
	array(
		'Value'=>'Row 1',
	),
	array(
		'Value'=>'Row 2',
	),
	array(
		'Value'=>'Row 3',
	),
	array(
		'Value'=>'Row 4',
	),
	array(
		'Value'=>'Row 5',
	),
	array(
		'Value'=>'Row 6',
	),
);

echo json_encode($rows);

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

To test out the shortcut syntax, try the following:

LIMIT: 2,1

or

LIMIT: 3

Refresh the report to see the changes.