04 Apr 08 _ CakePHP 1.2 Pagination Note

By casey
in CakePHP, Casey's Corner
I just noticed that in CakePHP 1.2 beta (6311), if you’re using the paginator helper, and attempting to sort data with the sort() function, AND you’re passing URL information, you need to specify the model explicitly in order to have the function take care of flipping the asc/desc sort direction.
Maybe this will make it more clear:
If I was just doing this:
< ?php
echo $paginator->sort('Name','name',array('url'=>Router::getParam('pass')));
?>
The generated sort link would always have the sort direction set to ‘asc’. Is this a bug? I’m not sure, probably. (Notice how I feed the Router’s pass params into the URL to preserve the current passed arguments to the controller function). To make this work, just specify the model explicitly:
< ?php
echo $paginator->sort('Name','name',array('url'=>Router::getParam('pass'),'model'=>'Image'));
?>
And now the sort direction in the generated URL will flip between ‘asc’ and ‘desc’ depending on the current listing.
Also, if you want to show the user which way we’re currently sorting, you can including the current sort direction as a class on the link:
< ?php
echo $paginator->sort('Name','name',array('url'=>Router::getParam('pass'),'model'=>'Image','class'=>$paginator->sortDir()));
?>
This will add the classes ‘asc’ or ‘desc’ to the link, and you can do some easy CSS styling to show directionality:
a.asc {
padding-right:20px;
background-image: url(../img/up-arrow.gif) top right no-repeat;
}
a.desc {
padding-right:20px;
background-image: url(../img/down-arrow.gif) top right no-repeat;
}
There’s lots more on pagination, make sure to check out the two Bakery articles: Basic Pagination Overview, and Advanced Pagination, both by Rob Conner.









December 23rd, 2009 at 4:50 pm
quote: “The generated sort link would always have the sort direction set to ‘asc’. Is this a bug?”
No it is not, you can actually change the default sort direction to ‘asc’ or ‘desc’ as follows:
force cakephp (using version 1.2.5) sort direction to ‘DESC’:
echo $paginator->sort(’Rating’, ‘rating’, array(’url’ => array(’direction’ => ‘desc’))).’ | ‘;
or flip it in your view yourself for a column:
$directionCreated = ‘desc’;
if ($paginator->sortKey(’Modelname’) == ‘Modelname.created’) {
if ($paginator->sortDir(’Modelname’) == ‘desc’ ) {
$directionCreated = ‘asc’;
}
}
echo $paginator->sort(’Datum’, ‘created’, array(’url’ => array(’direction’ => $directionCreated)));
This is actually documented in the CakePHP documentation: http://book.cakephp.org/view/656/Methods but not really clear that you can use it like this.
regards,
Steve