CakePHP: Extend PaginatorHelper to indicate sort field and direction
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
we should add some css codes to let desc/asc icon not covered...
table thead tr th a.asc {
background: url(../img/sort_asc.png) no-repeat right; padding: 16px;
}
table thead tr th a.desc {
background: url(../img/sort_desc.png) no-repeat right; padding: 16px;
}
Nice Article..
Thanks dear.. This is really helped me lot..
Doesn't work in Cakephp 1.2.x
Tested in Cakephp 1.2, in a working product and in a new installation, from scratch, it doesn't work (the helper class is not recognized)
Post new comment