How to create pagination for URL with parameters in codeigniter?
We have an application that has a page result based on certain parameters such as domain.com/index.php/welcome/student/male
here welcome
is a controller student
, this method name male
is a parameter, now we need pagination for this, but the problem is, a person can also use a subcategory like this domain.com/index.php/welcome/student/male/steven
, where steven
is another parameter, how to create pagination for this type of urls. Thank you in advance:)
Some issues with optional parameters along with pagination:
- Placing a page offset in the URL based on the number of parameters provided.
- If no additional parameters are set, paging offset will act as a parameter.
Method 1:
Use Query Strings for Pagination:
function student($gender, $category = NULL) {
$this->load->library('pagination');
$config['page_query_string'] = TRUE;
$config['query_string_segment'] = 'offset';
$config['base_url'] = base_url().'test/student/'.$gender;
// add the category if it set
if (!is_null($category))
$config['base_url'] = $config['base_url'].'/'.$category;
// make segment based URL ready to add query strings
// pagination library does not care if a ? is available
$config['base_url'] = $config['base_url'].'/?';
$config['total_rows'] = 200;
$config['per_page'] = 20;
$this->pagination->initialize($config);
// requested page:
$offset = $this->input->get('offset');
//...
}
Method 2:
Assuming it category
will never be a number, and if the last segment is a numeric value, then this page offset is not a functional parameter:
function student($gender, $category = NULL) {
// if the 4th segment is a number assume it as pagination rather than a category
if (is_numeric($this->uri->segment(4)))
$category = NULL;
$this->load->library('pagination');
$config['base_url'] = base_url().'test/student/'.$gender;
$config['uri_segment'] = 4;
// add the category if it set
if (!is_null($category)) {
$config['uri_segment'] = $config['uri_segment'] + 1;
$config['base_url'] = $config['base_url'].'/'.$category;
}
$config['total_rows'] = 200;
$config['per_page'] = 20;
$this->pagination->initialize($config);
// requested page:
$offset = ($this->uri->segment($config['uri_segment'])) ? $this->uri->segment($config['uri_segment']) : 1;
//...
}
I prefer the first method because it doesn't interfere with the functional parameters and it would be easier to implement pagination support at the abstract level.
I've worked with codeigniter but I think maybe you need to use config / routes.php. For example:
$route['^(bar1|bar2)/routes/(:any)/(:any)'] = "routes/get_bar/$2/$3";
you could write a function in the controller (routes in this case) like this:
public function get_bar($bar1 = null, $bar2 = null)
I hope this helps you Hi!