CakePHP: Extend PaginatorHelper to indicate sort field and direction

Richard's picture

Here's a quick piece of code that extends the default CakePHP PaginatorHelper
to add css classes to the sort column links to indicate which field is being sorted by,
and which direction:

/app/views/helpers/ex_paginator.php:

/**
 * Extends the PaginatorHelper
 */
 
App::import('Helper', 'Paginator');
 
class ExPaginatorHelper extends PaginatorHelper {
 
	/**
	 * Adds and 'asc' or 'desc' class to the sort links
	 * @see /cake/libs/view/helpers/PaginatorHelper#sort($title, $key, $options)
	 */
	function sort($title, $key = null, $options = array()) {
 
		// get current sort key & direction
		$sortKey = $this->sortKey();
		$sortDir = $this->sortDir();
 
		// add $sortDir class if current column is sort column
		if ($sortKey == $key && $key !== null) {
 
			$options['class'] = $sortDir;
 
		}
 
		return parent::sort($title, $key, $options);
 
	}
 
}

Usage:

Add "ExPaginator" to your list of helpers and then use $exPaginator where you would usually use $paginator in your views. For example:

<table>
	<tr>
		<th><?php $echo $exPaginator->sort("Name", "Model.name") ?></th>
	</tr>
<?php foreach($data as $item): ?>
	<tr>
		<td><?php echo $item['Model']['name'] ?></td>
	</tr>
<?php endforeach; ?>
</table>

Output (after clicking the table header):

<table>
	<tr>
		<th><a href='...' class='asc'></a></th>
	</tr>
...
</table>

Styling:

The anchor tag of the current sort column will have a class of either 'asc' or 'desc' depending on the sort order. You can style it with the following rules:

table tr th a {
	padding-right: 16px;
}
table tr th a.asc {
	background: url(../img/sort_asc.gif) no-repeat right center;
}
table tr th a.desc {
	background: url(../img/sort_desc.gif) no-repeat right center;
}

Happy baking! :-)

Comments

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options