Filter, sort and paginate in Codeigniter


Ive recently started using CodeIgniter as I was searching for a very lightweight framework and it seemed to come up as a top choice.

I am new to the whole MVC thing, enjoying it but am stuck with something which seems very simple.

I am coding a CMS and need a way to filter, sort and paginate the results. I am used to doing it with querystrings, so I would have something along the lines of:


I have no idea how I would go about doing this in CI so I just turned on the EnableQueryStrings in the config and it works fine, but i am getting the feeling its probably not the most elegant solution.

I suppose I could have


but to me this seems very inflexible, what if for example i dont need to sort, how would i make sure i am looking at the correct uri segment?

any ideas?

3/11/2010 9:04:04 PM

Accepted Answer

Have you tried implementing the _remap function? It will redirect all queries to the controller to that function allowing you to implement as many (or as few) of those as you like.

You could then do something like this:

class Articles extends Controller
    // Note: No need for a "order" or even an "index" function!
    public function _remap()
        $assoc = $this->uri->uri_to_assoc( 4 );
        /* $assoc is now 
           array( "order"=>"title",
                  "page"=>5); */
3/11/2010 10:01:11 PM

I've run into this problem a ton of times and finally decided to try to solve it properly.

My solution involves a combo path/query string approach (it requires a solution like the one Stephen linked to).

URLs are formatted like so:

These optional $_GET params can then be used as query conditions, and you can use as many as you want without screwing up CI's pagination offset.

By default, CodeIgniter's Pagination library doesn't support placing the offset before the end of the URI. The trick to getting CI to support this is to extend the pagination library like so:

Then, in your controller, you can initialize pagination like so:

$config['url_format'] = site_url('controller/index/{offset}?'.http_build_query($params));
$config['total_rows'] = $this->model->count_rows();
$config['per_page'] = 5;

Note that no uri_segment is required, because the custom Pagination::initialize method detects it based on where {offset} falls in the url_format string.

Links that are built with $this->pagination->create_links() will insert the offset in the appropriate place, and preserve the tailing query string.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow