Displaying sort direction in paginated data

Just a little tip on styling your table with paginated data…

Wouldn’t it be nice to show to the user what column and direction is currently used for sorting of your data? Here’s how you can do that with a little CSS and some Paginator methods.

First, we need to find out in our view which column we use to sort and in what direction (ASC or DESC) the sorting goes:

$sortDir = $paginator->sortDir();
$sortKey = $paginator->sortKey();

Now that we know the two values, we can easily style the table header:

<th <?php echo ($sortKey == 'ID') ? 'class="'.$sortDir.'"' : ''; ?>>

In the example above, if our sorting field happens to be “ID” we assign a class=”asc” (for ascending) or class=”desc” (for descending), else no class is assigned.
This code uses a short-hand if/else condition, which is sometimes frowned upon, but I feel in this case it provides for a cleaner looking code.

CSS files and $scripts_for_layout

You probably know that if you have $scripts_for_layout in your site’s layout, then you can include JS files from the view. For example, if you’d like to include ‘myScript.js’ from some view you would add the following code: $javascript->link(‘myScript’, false);

Basically the second param (false), will tell CakePHP not to include the file in-line, but rather where the $scripts_for_layout is located.

A less known feature is that you can do the same for your CSS files. So, if you need to include some style that is specific to a given view, add something like this to your view file:

$html->css(‘myViewCss’, ‘stylesheet’, array(“media”=>”all” ), false);

Again, you simply need to specify a ‘false’ parameter. This will tell CakePHP to include the CSS file where the $scripts_for_layout variable is located (which should be in the <head>).