Filter, sort and paginate in Codeigniter Filter, sort and paginate in Codeigniter codeigniter codeigniter

Filter, sort and paginate in Codeigniter


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",                  "sort"=>"desc",                  "filter"=>"articletitle",                   "page"=>5); */    }}


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:

http://www.myapp.dev/controller/index/10?order_by=id+asc&status=open

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: http://pastie.org/1393513

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;$this->pagination->initialize($config);

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.


I don't like the fact that CodeIgniter destroys the query string. The query string is great for optional parameters. Trying to put optional parameters in URI segments and things start to get weird.

A URL like this seems a bit of a hack :

index.php/articles/index/order/title/sort/desc/filter/articletitle/page/5

For this reason I configure CodeIgniter to use a mixture of URI segments and query string. This answer shows you how you can achieve this.