CodeIgniter: pagination doesn't have question mark? - codeigniter

The code below generates pagination using query strings. However, there is no leading ?. So, I get something like this: http://localhost/index.php/search/&limit=10. Any ideas why?
this->load->library('pagination');
$config = array();
$config['base_url'] = 'http://localhost/index.php/search/';
$config['total_rows'] = 200;
$config['per_page'] = 10;
$config['num_links'] = 4;
$config['full_tag_open'] = '<ol>';
$config['full_tag_close'] = '</ol>';
$config['first_link'] = 'First';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['last_link'] = 'Last';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['next_link'] = 'Next';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$config['prev_link'] = 'Previous';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li class="active">';
$config['cur_tag_close'] = '</li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$this->pagination->initialize($config);
echo ($this->pagination->create_links());
EDIT 1:
http://codeigniter.com/forums/viewthread/161263/
EDIT 2:
The docs seem to suggest that what I did should work: http://codeigniter.com/user_guide/libraries/pagination.html
$config['page_query_string'] = TRUE;
By default, the pagination library assume you are using URI Segments, and constructs your links something like
http://example.com/index.php/test/page/20
If you have $config['enable_query_strings'] set to TRUE your links will automatically be re-written using Query Strings. This option can also be explictly set. Using $config['page_query_string'] set to TRUE, the pagination link will become.
http://example.com/index.php?c=test&m=page&per_page=20

I've run into this myself. When using query strings, CodeIgniter has to assume you have other query string parameters (BUT, CI assumes you're using query string parameters to map your controller and method...). I like using query string for stuff like filtering results and such, while still using the basic routing options in the URI (like you).
I've had to live with the ?& personally, but I suppose you could extend the Pagination library like so (long function, sorry):
class MY_Pagination extends CI_Pagination {
function create_links()
{
// If our item count or per-page total is zero there is no need to continue.
if ($this->total_rows == 0 OR $this->per_page == 0)
{
return '';
}
// Calculate the total number of pages
$num_pages = ceil($this->total_rows / $this->per_page);
// Is there only one page? Hm... nothing more to do here then.
if ($num_pages == 1)
{
return '';
}
// Determine the current page number.
$CI =& get_instance();
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
if ($CI->input->get($this->query_string_segment) != 0)
{
$this->cur_page = $CI->input->get($this->query_string_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
else
{
if ($CI->uri->segment($this->uri_segment) != 0)
{
$this->cur_page = $CI->uri->segment($this->uri_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
$this->num_links = (int)$this->num_links;
if ($this->num_links < 1)
{
show_error('Your number of links must be a positive number.');
}
if ( ! is_numeric($this->cur_page))
{
$this->cur_page = 0;
}
// Is the page number beyond the result range?
// If so we show the last page
if ($this->cur_page > $this->total_rows)
{
$this->cur_page = ($num_pages - 1) * $this->per_page;
}
$uri_page_number = $this->cur_page;
$this->cur_page = floor(($this->cur_page/$this->per_page) + 1);
// Calculate the start and end numbers. These determine
// which number to start and end the digit links with
$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
$end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
// Is pagination being used over GET or POST? If get, add a per_page query
// string. If post, add a trailing slash to the base URL if needed
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
$this->base_url = str_replace('?&', '?', rtrim($this->base_url).'&'.$this->query_string_segment.'=');
}
else
{
$this->base_url = rtrim($this->base_url, '/') .'/';
}
// And here we go...
$output = '';
// Render the "First" link
if ($this->first_link !== FALSE AND $this->cur_page > ($this->num_links + 1))
{
$first_url = ($this->first_url == '') ? $this->base_url : $this->first_url;
$output .= $this->first_tag_open.'<a '.$this->anchor_class.'href="'.$first_url.'">'.$this->first_link.'</a>'.$this->first_tag_close;
}
// Render the "previous" link
if ($this->prev_link !== FALSE AND $this->cur_page != 1)
{
$i = $uri_page_number - $this->per_page;
if ($i == 0 && $this->first_url != '')
{
$output .= $this->prev_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$this->prev_link.'</a>'.$this->prev_tag_close;
}
else
{
$i = ($i == 0) ? '' : $this->prefix.$i.$this->suffix;
$output .= $this->prev_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$i.'">'.$this->prev_link.'</a>'.$this->prev_tag_close;
}
}
// Render the pages
if ($this->display_pages !== FALSE)
{
// Write the digit links
for ($loop = $start -1; $loop <= $end; $loop++)
{
$i = ($loop * $this->per_page) - $this->per_page;
if ($i >= 0)
{
if ($this->cur_page == $loop)
{
$output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page
}
else
{
$n = ($i == 0) ? '' : $i;
if ($n == '' && $this->first_url != '')
{
$output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$loop.'</a>'.$this->num_tag_close;
}
else
{
$n = ($n == '') ? '' : $this->prefix.$n.$this->suffix;
$output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$n.'">'.$loop.'</a>'.$this->num_tag_close;
}
}
}
}
}
// Render the "next" link
if ($this->next_link !== FALSE AND $this->cur_page < $num_pages)
{
$output .= $this->next_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.($this->cur_page * $this->per_page).$this->suffix.'">'.$this->next_link.'</a>'.$this->next_tag_close;
}
// Render the "Last" link
if ($this->last_link !== FALSE AND ($this->cur_page + $this->num_links) < $num_pages)
{
$i = (($num_pages * $this->per_page) - $this->per_page);
$output .= $this->last_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.$i.$this->suffix.'">'.$this->last_link.'</a>'.$this->last_tag_close;
}
// Kill double slashes. Note: Sometimes we can end up with a double slash
// in the penultimate link so we'll kill all double slashes.
$output = preg_replace("#([^:])//+#", "\\1/", $output);
// Add the wrapper HTML if exists
$output = $this->full_tag_open.$output.$this->full_tag_close;
return $output;
}
}

Related

Codeigniter 3.1.0 & Bootstrap Pagination Links

On my codeigniter pagination links I am using bootstrap 3 +
When I am on the very first link it hides the << which goes back to start when I click on it.
1 2 >>
Question How can I make the codeigniter pagination all ways display << >> I have tried Always show Previous & Next links using CodeIgniter Pagination Class but is for CI2
$config['base_url'] = base_url('forum/?fid=' . $this->input->get('fid') . $url);
$config['total_rows'] = $this->thread_model->total_threads($this->input->get('fid'));
$config['per_page'] = $this->config->item('config_limit_admin');
$config['page_query_string'] = TRUE;
$config["full_tag_open"] = '<ul class="pagination">';
$config["full_tag_close"] = '</ul>';
$config["first_link"] = "«";
$config["first_tag_open"] = "<li>";
$config["first_tag_close"] = "</li>";
$config["last_link"] = "»";
$config["last_tag_open"] = "<li>";
$config["last_tag_close"] = "</li>";
$config['next_link'] = '»';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '<li>';
$config['prev_link'] = '«';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '<li>';
$config['cur_tag_open'] = '<li class="active"><a href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
I have just override the create_links() of core library in slightly different way to achieve this. So All you have to do is create a file name My_Pagination.php inapplication/libraries and put this code there (Code copied from create_link() method from core library Pagination.php)
My_Pagination.php file (Codeigniter 3.1.0)
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Pagination extends CI_Pagination {
public function create_links() {
if ($this->total_rows == 0 OR $this->per_page == 0) {
return '';
}
// Calculate the total number of pages
$num_pages = (int) ceil($this->total_rows / $this->per_page);
if ($num_pages === 1) {
return '';
}
// Check the user defined number of links.
$this->num_links = (int) $this->num_links;
if ($this->num_links < 0) {
show_error('Your number of links must be a non-negative number.');
}
// Keep any existing query string items.
// Note: Has nothing to do with any other query string option.
if ($this->reuse_query_string === TRUE) {
$get = $this->CI->input->get();
// Unset the controll, method, old-school routing options
unset($get['c'], $get['m'], $get[$this->query_string_segment]);
} else {
$get = array();
}
// Put together our base and first URLs.
// Note: DO NOT append to the properties as that would break successive calls
$base_url = trim($this->base_url);
$first_url = $this->first_url;
$query_string = '';
$query_string_sep = (strpos($base_url, '?') === FALSE) ? '?' : '&';
// Are we using query strings?
if ($this->page_query_string === TRUE) {
// If a custom first_url hasn't been specified, we'll create one from
// the base_url, but without the page item.
if ($first_url === '') {
$first_url = $base_url;
// If we saved any GET items earlier, make sure they're appended.
if (!empty($get)) {
$first_url .= $query_string_sep . http_build_query($get);
}
}
// Add the page segment to the end of the query string, where the
// page number will be appended.
$base_url .= $query_string_sep . http_build_query(array_merge($get, array($this->query_string_segment => '')));
} else {
// Standard segment mode.
// Generate our saved query string to append later after the page number.
if (!empty($get)) {
$query_string = $query_string_sep . http_build_query($get);
$this->suffix .= $query_string;
}
// Does the base_url have the query string in it?
// If we're supposed to save it, remove it so we can append it later.
if ($this->reuse_query_string === TRUE && ($base_query_pos = strpos($base_url, '?')) !== FALSE) {
$base_url = substr($base_url, 0, $base_query_pos);
}
if ($first_url === '') {
$first_url = $base_url . $query_string;
}
$base_url = rtrim($base_url, '/') . '/';
}
// Determine the current page number.
$base_page = ($this->use_page_numbers) ? 1 : 0;
// Are we using query strings?
if ($this->page_query_string === TRUE) {
$this->cur_page = $this->CI->input->get($this->query_string_segment);
} elseif (empty($this->cur_page)) {
// Default to the last segment number if one hasn't been defined.
if ($this->uri_segment === 0) {
$this->uri_segment = count($this->CI->uri->segment_array());
}
$this->cur_page = $this->CI->uri->segment($this->uri_segment);
// Remove any specified prefix/suffix from the segment.
if ($this->prefix !== '' OR $this->suffix !== '') {
$this->cur_page = str_replace(array($this->prefix, $this->suffix), '', $this->cur_page);
}
} else {
$this->cur_page = (string) $this->cur_page;
}
// If something isn't quite right, back to the default base page.
if (!ctype_digit($this->cur_page) OR ( $this->use_page_numbers && (int) $this->cur_page === 0)) {
$this->cur_page = $base_page;
} else {
// Make sure we're using integers for comparisons later.
$this->cur_page = (int) $this->cur_page;
}
// Is the page number beyond the result range?
// If so, we show the last page.
if ($this->use_page_numbers) {
if ($this->cur_page > $num_pages) {
$this->cur_page = $num_pages;
}
} elseif ($this->cur_page > $this->total_rows) {
$this->cur_page = ($num_pages - 1) * $this->per_page;
}
$uri_page_number = $this->cur_page;
// If we're using offset instead of page numbers, convert it
// to a page number, so we can generate the surrounding number links.
if (!$this->use_page_numbers) {
$this->cur_page = (int) floor(($this->cur_page / $this->per_page) + 1);
}
// Calculate the start and end numbers. These determine
// which number to start and end the digit links with.
$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
$end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
// And here we go...
$output = '';
// Render the "First" link.
if ($this->first_link !== FALSE && $this->cur_page > ($this->num_links + 1 + !$this->num_links)) {
// Take the general parameters, and squeeze this pagination-page attr in for JS frameworks.
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, 1);
$output .= $this->first_tag_open . '<a href="' . $first_url . '"' . $attributes . $this->_attr_rel('start') . '>'
. $this->first_link . '</a>' . $this->first_tag_close;
}
// Render the "Previous" link.
//if ($this->prev_link !== FALSE && $this->cur_page !== 1)
if ($this->prev_link !== FALSE) {//REMOVED $this->cur_page !== 1
$i = ($this->use_page_numbers) ? $uri_page_number - 1 : $uri_page_number - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, ($this->cur_page - 1));
if ($i === $base_page || $this->cur_page == 1) {//ADDED $this->cur_page == 1
// First page
$output .= $this->prev_tag_open . '<a href="' . $first_url . '"' . $attributes . $this->_attr_rel('prev') . '>'
. $this->prev_link . '</a>' . $this->prev_tag_close;
} else {
$append = $this->prefix . $i . $this->suffix;
$output .= $this->prev_tag_open . '<a href="' . $base_url . $append . '"' . $attributes . $this->_attr_rel('prev') . '>'
. $this->prev_link . '</a>' . $this->prev_tag_close;
}
}
// Render the pages
if ($this->display_pages !== FALSE) {
// Write the digit links
for ($loop = $start - 1; $loop <= $end; $loop++) {
$i = ($this->use_page_numbers) ? $loop : ($loop * $this->per_page) - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $loop);
if ($i >= $base_page) {
if ($this->cur_page === $loop) {
// Current page
$output .= $this->cur_tag_open . $loop . $this->cur_tag_close;
} elseif ($i === $base_page) {
// First page
$output .= $this->num_tag_open . '<a href="' . $first_url . '"' . $attributes . $this->_attr_rel('start') . '>'
. $loop . '</a>' . $this->num_tag_close;
} else {
$append = $this->prefix . $i . $this->suffix;
$output .= $this->num_tag_open . '<a href="' . $base_url . $append . '"' . $attributes . '>'
. $loop . '</a>' . $this->num_tag_close;
}
}
}
}
// Render the "next" link
//if ($this->next_link !== FALSE && $this->cur_page < $num_pages)
if ($this->next_link !== FALSE) {//REMOVED $this->cur_page < $num_pages
$i = ($this->use_page_numbers) ? $this->cur_page + 1 : $this->cur_page * $this->per_page;
if($this->cur_page == $num_pages){//WHEN LAST LINK
$i = $num_pages;
}
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $this->cur_page + 1);
$output .= $this->next_tag_open . '<a href="' . $base_url . $this->prefix . $i . $this->suffix . '"' . $attributes
. $this->_attr_rel('next') . '>' . $this->next_link . '</a>' . $this->next_tag_close;
}
// Render the "Last" link
if ($this->last_link !== FALSE && ($this->cur_page + $this->num_links + !$this->num_links) < $num_pages) {
$i = ($this->use_page_numbers) ? $num_pages : ($num_pages * $this->per_page) - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $num_pages);
$output .= $this->last_tag_open . '<a href="' . $base_url . $this->prefix . $i . $this->suffix . '"' . $attributes . '>'
. $this->last_link . '</a>' . $this->last_tag_close;
}
$output = preg_replace('#([^:"])//+#', '\\1/', $output);
return $this->full_tag_open . $output . $this->full_tag_close;
}
}
Just removed 2 condition
$this->cur_page !== 1 (This is below // Render the "Previous" link COMMENT)
$this->cur_page < $num_pages (This is below // Render the "next" link COMMENT)
Added 2 condition
if ($i === $base_page){... changed this as if ($i === $base_page || $this->cur_page == 1) {...
Added this inside if ($this->next_link !== FALSE) {... condition
if($this->cur_page == $num_pages){
$i = $num_pages;
}
None you have to do except putting this file in libraries directory and now your << and >> links will show always even you may change it in config as normal configuration
Well, you'll have to modify the create_links of the Pagination class. What I'd do it's extending the system/libraries/Pagination.php class with a MY_Pagination.php, so you override the behaviour and you can modify it accordingly to your preferences.
By the way, checking the class, I think you should look into lines 563 on:
// Render the "First" link.
if ($this->first_link !== FALSE && $this->cur_page > ($this->num_links + 1 + ! $this->num_links))
{
// Take the general parameters, and squeeze this pagination-page attr in for JS frameworks.
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, 1);
$output .= $this->first_tag_open.'<a href="'.$first_url.'"'.$attributes.$this->_attr_rel('start').'>'
.$this->first_link.'</a>'.$this->first_tag_close;
}
You'll have to take care of the if condition to always render the link.

How to properly generate URL with more then one argument

How to generate URL in my current code, so I can pass the values to my directions function.
This is my code for displaying markers on map for each company:
$n = 0;
foreach ($firm as $f) {
if ($f->active == 1 && in_array($f->skd_n, $dejavnost) && $f->lat != 0) {
$lat_f = $f->lat;
$lng_f = $f->lng;
$distance = (($this->distance($lat, $lng, $lat_f, $lng_f)) * 1000);
if ($distance <= $rad && $n <= 199) {
$marker = array();
$marker['position'] = "$lat_f, $lng_f";
if ($f->phone != 0) {
$marker['infowindow_content'] = '<div class="info_window">' . "$f->title" . '<br/>' .
'<div class="pin_icon"></div>' .
"$f->address" . '<br/>' .
'<div class="phone_icon"></div>' .
"$f->phone" . '<br/>' .
//generate URL with 4 arguments
'DIRECTION' .
'</div><br/>';
}else{
$marker['infowindow_content'] = '<div class="info_window">' . "$f->title" . '<br/>' .
'<div class="pin_icon"></div>' .
"$f->address" . '</div>';
}
$marker['animation'] = 'DROP';
$marker['zIndex'] = '0';
$marker['icon'] = '../images/pin-map-red.png';
$this->googlemaps->add_marker($marker);
$n++;
}
}
}
I want to add anchor to next function, where question marks are and use variables (coordinates) as arguments:
function direction($lat, $lng, $lat_f, $lng_f){
$config['places'] = TRUE;
$config['placesAutocompleteInputID'] = 'event_location';
$config['placesAutocompleteBoundsMap'] = TRUE;
$config['zoom'] = 'auto';
$config['center'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = "$lat, $lng";
$config['directionsEnd'] = "$lat_f, $lng_f";
$config['directionsDivID'] = 'directions';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
$this->load->view('header', $data);
$this->load->view('domov_view', $data);
$this->load->view('footer');
}
How can I use values in second function (direction) from first?
Thank you!
You could pass the arguments in url and fetch them inside your direction method via $_GET method
Example:
You could generate link like that
DIRECTION
So your function would look like this:
$n = 0;
foreach ($firm as $f) {
if ($f->active == 1 && in_array($f->skd_n, $dejavnost) && $f->lat != 0) {
$lat_f = $f->lat;
$lng_f = $f->lng;
$distance = (($this->distance($lat, $lng, $lat_f, $lng_f)) * 1000);
if ($distance <= $rad && $n <= 199) {
$marker = array();
$marker['position'] = "$lat_f, $lng_f";
if ($f->phone != 0) {
$marker['infowindow_content'] = '<div class="info_window">' . "$f->title" . '<br/>' .
'<div class="pin_icon"></div>' .
"$f->address" . '<br/>' .
'<div class="phone_icon"></div>' .
"$f->phone" . '<br/>' .
'DIRECTION' .
'</div><br/>';
}else{
$marker['infowindow_content'] = '<div class="info_window">' . "$f->title" . '<br/>' .
'<div class="pin_icon"></div>' .
"$f->address" . '</div>';
}
$marker['animation'] = 'DROP';
$marker['zIndex'] = '0';
$marker['icon'] = '../images/pin-map-red.png';
$this->googlemaps->add_marker($marker);
$n++;
}
}
}
And fetch them this way in directions function
function direction(){
$lat = $this->input->get('lat');
$lng = $this->input->get('lng');
$lat_f = $this->input->get('lat_f');
$lng_f = $this->input->get('lng_f');
$config['places'] = TRUE;
$config['placesAutocompleteInputID'] = 'event_location';
$config['placesAutocompleteBoundsMap'] = TRUE;
$config['zoom'] = 'auto';
$config['center'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = "$lat, $lng";
$config['directionsEnd'] = "$lat_f, $lng_f";
$config['directionsDivID'] = 'directions';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
$this->load->view('header', $data);
$this->load->view('domov_view', $data);
$this->load->view('footer');
}
P.S.: If you are sending langitude and longitude via url you will probably have problems with sending disallowed chars via url (dot(.)).
You can configure allowed url chars in config file
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_=+-'
You can extend url helper. Add function some:
create_url('controller/action', [
'getParam1' => 'value1',
'getParam2' => 'value2',
'getParam3' => 'value3',
]);
And it generate http://base.url/controller/action?getParam1=value&getParam2=value2&getParam3=value3
or use
http://www.codeigniter.com/userguide2/libraries/uri.html
create link $this->uri->assoc_to_uri()
parse link $this->uri->uri_to_assoc()

codeigniter pagination result change

When I am on the first page of my codeigniter pagination my result should display Showing 1 to 1 of 3 (3 Pages) currently the first page is starts at 0 Showing 0 to 0 of 3 (3 Pages)
The page number is the uri segment(3). How can I fix my code so that the fist page is 1 Showing 1 to 1 of 3 (3 Pages)
$page_number = $this->uri->segment(3);
if (isset($page_number)) {
$page = $page_number;
} else {
$page = 1;
}
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_group_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_group_total - $admin_limit)) ? $user_group_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_group_total, ceil($user_group_total / $admin_limit));
Controller:
public function index($offset = 0) {
$this->load->model('admin/user/model_user_group');
$this->load->library('pagination');
$data['title'] = "Users Group";
$success = $this->session->userdata('success');
if (isset($success)) {
$data['success'] = $this->session->userdata('success');
$this->session->unset_userdata('success');
} else {
$data['success'] = '';
}
$page_number = $this->uri->segment(3);
if (isset($page_number)) {
$page = $page_number;
} else {
$page = 1;
}
$admin_limit = 1;
$user_group_total = $this->model_user_group->getTotalUserGroups();
$results = $this->model_user_group->getUserGroups($admin_limit, $this->uri->segment(3));
$config['base_url'] = base_url() . 'admin/users_group';
$config['total_rows'] = $user_group_total;
$config['per_page'] = $admin_limit;
$config['uri_segment'] = 3;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] ="</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
foreach ($results as $result) {
$data['user_groups'][] = array(
'user_group_id' => $result['user_group_id'],
'name' => $result['name'],
'edit' => site_url('admin/users_group/edit' .'/'. $result['user_group_id'])
);
}
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_group_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_group_total - $admin_limit)) ? $user_group_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_group_total, ceil($user_group_total / $admin_limit));
$this->load->view('template/user/users_group_list.tpl', $data);
}
I have fixed the result out put.
It need to be changed around so page 1 would be come page 0
Old
if (isset($page_number)) {
$page = $page_number;
} else {
$page = 1;
}
New
if (isset($page_number)) {
$page = $page_number;
} else {
$page = 0;
}
Result
Old
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_group_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_group_total - $admin_limit)) ? $user_group_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_group_total, ceil($user_group_total / $admin_limit));
New
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_group_total) ? (($page - 0) * $admin_limit) + 1 : 0, ((($page - 0) * $admin_limit) > ($user_group_total - $admin_limit)) ? $user_group_total : ((($page - 0) * $admin_limit) + $admin_limit), $user_group_total, ceil($user_group_total / $admin_limit));

joomla pagination shows same result on every page

I have page of articles with more than 5 results. 5 results are displayed per page. Pagination shows up. When I go to different pages however, every page has the same 5 results.
My getItems():
function getItems()
{
$params = $this->getState()->get('params');
$limit = $this->getState('list.limit');
// 5
if ($this->_articles === null && $category = $this->getCategory()) {
$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
$model->setState('params', JFactory::getApplication()->getParams());
$model->setState('filter.category_id', $category->id);
$model->setState('filter.published', $this->getState('filter.published'));
$model->setState('filter.access', $this->getState('filter.access'));
$model->setState('filter.language', $this->getState('filter.language'));
$model->setState('list.ordering', $this->_buildContentOrderBy());
$model->setState('list.start', $this->getState('list.start'));
$model->setState('list.limit', $limit);
$model->setState('list.direction', $this->getState('list.direction'));
$model->setState('list.filter', $this->getState('list.filter'));
// filter.subcategories indicates whether to include articles from subcategories in the list or blog
$model->setState('filter.subcategories', $this->getState('filter.subcategories'));
$model->setState('filter.max_category_levels', $this->setState('filter.max_category_levels'));
$model->setState('list.links', $this->getState('list.links'));
if ($limit >= 0) {
$this->_articles = $model->getItems();
if ($this->_articles === false) {
$this->setError($model->getError());
}
}
else {
$this->_articles=array();
}
$this->_pagination = $model->getPagination();
}
$filterResult = null;
return $this->_articles;
}
My populate state:
protected function populateState($ordering = null, $direction = null)
{
// Initiliase variables.
$app = JFactory::getApplication('site');
$pk = JRequest::getInt('id');
$this->setState('category.id', $pk);
// Load the parameters. Merge Global and Menu Item params into new object
$params = $app->getParams();
$menuParams = new JRegistry;
if ($menu = $app->getMenu()->getActive()) {
$menuParams->loadString($menu->params);
}
$mergedParams = clone $menuParams;
$mergedParams->merge($params);
$this->setState('params', $mergedParams);
$user = JFactory::getUser();
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
$groups = implode(',', $user->getAuthorisedViewLevels());
if ((!$user->authorise('core.edit.state', 'com_content')) && (!$user->authorise('core.edit', 'com_content'))){
// limit to published for people who can't edit or edit.state.
$this->setState('filter.published', 1);
/**
* Custom Author Filter
*/
if (JRequest::getVar('author')) {
$this->setState('filter.created_by', $this->getUserId(JRequest::getVar('author')));
}
// Filter by start and end dates.
$nullDate = $db->Quote($db->getNullDate());
$nowDate = $db->Quote(JFactory::getDate()->toMySQL());
$query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')');
$query->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
/**
* Custom Author Filter
*/
if (JRequest::getVar('author')) {
$query->where('(a.created_by = "' . $this->getUserId(JRequest::getVar('author')) . '")');
}
}
// process show_noauth parameter
if (!$params->get('show_noauth')) {
$this->setState('filter.access', true);
}
else {
$this->setState('filter.access', false);
}
// Optional filter text
$this->setState('list.filter', JRequest::getString('filter-search'));
// filter.order
$itemid = JRequest::getInt('id', 0) . ':' . JRequest::getInt('Itemid', 0);
$orderCol = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.filter_order', 'filter_order', '', 'string');
if (!in_array($orderCol, $this->filter_fields)) {
$orderCol = 'a.ordering';
}
$this->setState('list.ordering', $orderCol);
$listOrder = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.filter_order_Dir',
'filter_order_Dir', '', 'cmd');
if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', ''))) {
$listOrder = 'ASC';
}
$this->setState('list.direction', $listOrder);
//$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));
// set limit for query. If list, use parameter. If blog, add blog parameters for limit.
if ((JRequest::getCmd('layout') == 'blog') || $params->get('layout_type') == 'blog') {
$limit = $params->get('num_leading_articles') + $params->get('num_intro_articles') + $params->get('num_links');
$this->setState('list.links', $params->get('num_links'));
}
else {
$limit = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.limit', 'limit', $params->get('display_num'));
}
$this->setState('list.limit', $limit);
// set the depth of the category query based on parameter
$showSubcategories = $params->get('show_subcategory_content', '0');
if ($showSubcategories) {
$this->setState('filter.max_category_levels', $params->get('show_subcategory_content', '1'));
$this->setState('filter.subcategories', true);
}
$this->setState('filter.language',$app->getLanguageFilter());
$this->setState('layout', JRequest::getCmd('layout'));
}
My display function de view.html.php
function display($tpl = null)
{
$app = JFactory::getApplication();
$user = JFactory::getUser();
// Get some data from the models
$state = $this->get('State');
$params = $state->params;
$items = $this->get('Items');
$contactId = JRequest::getVar('author');
if($contactId){
$this->setUserId($contactId);
$this->setContactName($this->userId);
}
$category = $this->get('Category');
$children = $this->get('Children');
$parent = $this->get('Parent');
$pagination = $this->get('Pagination');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
JError::raiseError(500, implode("\n", $errors));
return false;
}
if ($category == false) {
return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
}
if ($parent == false) {
return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
}
// Setup the category parameters.
$cparams = $category->getParams();
$category->params = clone($params);
$category->params->merge($cparams);
// Check whether category access level allows access.
$user = JFactory::getUser();
$groups = $user->getAuthorisedViewLevels();
if (!in_array($category->access, $groups)) {
return JError::raiseError(403, JText::_("JERROR_ALERTNOAUTHOR"));
}
// PREPARE THE DATA
// Get the metrics for the structural page layout.
$numLeading = $params->def('num_leading_articles', 1);
$numIntro = $params->def('num_intro_articles', 4);
$numLinks = $params->def('num_links', 4);
// Compute the article slugs and prepare introtext (runs content plugins).
for ($i = 0, $n = count($items); $i < $n; $i++)
{
$item = &$items[$i];
$item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id;
// No link for ROOT category
if ($item->parent_alias == 'root') {
$item->parent_slug = null;
}
$item->event = new stdClass();
$dispatcher = JDispatcher::getInstance();
// Ignore content plugins on links.
if ($i < $numLeading + $numIntro) {
$item->introtext = JHtml::_('content.prepare', $item->introtext);
$results = $dispatcher->trigger('onContentAfterTitle', array('com_content.article', &$item, &$item->params, 0));
$item->event->afterDisplayTitle = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentBeforeDisplay', array('com_content.article', &$item, &$item->params, 0));
$item->event->beforeDisplayContent = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentAfterDisplay', array('com_content.article', &$item, &$item->params, 0));
$item->event->afterDisplayContent = trim(implode("\n", $results));
}
}
// Check for layout override only if this is not the active menu item
// If it is the active menu item, then the view and category id will match
$active = $app->getMenu()->getActive();
if ((!$active) || ((strpos($active->link, 'view=category') === false) || (strpos($active->link, '&id=' . (string) $category->id) === false))) {
// Get the layout from the merged category params
if ($layout = $category->params->get('category_layout')) {
$this->setLayout($layout);
}
}
// At this point, we are in a menu item, so we don't override the layout
elseif (isset($active->query['layout'])) {
// We need to set the layout from the query in case this is an alternative menu item (with an alternative layout)
$this->setLayout($active->query['layout']);
}
// For blog layouts, preprocess the breakdown of leading, intro and linked articles.
// This makes it much easier for the designer to just interrogate the arrays.
if (($params->get('layout_type') == 'blog') || ($this->getLayout() == 'blog')) {
$max = count($items);
// The first group is the leading articles.
$limit = $numLeading;
for ($i = 0; $i < $limit && $i < $max; $i++) {
$this->lead_items[$i] = &$items[$i];
}
// The second group is the intro articles.
$limit = $numLeading + $numIntro;
// Order articles across, then down (or single column mode)
for ($i = $numLeading; $i < $limit && $i < $max; $i++) {
$this->intro_items[$i] = &$items[$i];
}
$this->columns = max(1, $params->def('num_columns', 1));
$order = $params->def('multi_column_order', 1);
if ($order == 0 && $this->columns > 1) {
// call order down helper
$this->intro_items = ContentHelperQuery::orderDownColumns($this->intro_items, $this->columns);
}
$limit = $numLeading + $numIntro + $numLinks;
// The remainder are the links.
for ($i = $numLeading + $numIntro; $i < $limit && $i < $max;$i++)
{
$this->link_items[$i] = &$items[$i];
}
}
$children = array($category->id => $children);
//Escape strings for HTML output
$this->pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
$this->assign('maxLevel', $params->get('maxLevel', -1));
$this->assignRef('state', $state);
$this->assignRef('items', $items);
$this->assignRef('category', $category);
$this->assignRef('children', $children);
$this->assignRef('params', $params);
$this->assignRef('parent', $parent);
$this->assignRef('pagination', $pagination);
$this->assignRef('user', $user);
$this->_prepareDocument();
parent::display($tpl);
}
If i print the contents of $pagination in the view.html.php here:
$this->_prepareDocument();
echo '<pre>'; print_r($pagination); exit();
parent::display($tpl);
I get the following results:
In my template file I echo the pagination:
<?php echo $this->pagination->getPagesLinks(); ?>
By the way, clicking on 'next' does change the url into ...?start=5.
This line in populateState is commented out
$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));
Uncomment it change it tot get the "start" parameter:
$this->setState('list.start', JRequest::getVar('start', 0, '', 'int'));

issue with pagination and limit

I have 3 tables site_settings,sermons & Preachers. In site_settings table, set the max number of preachers to be displayed. Preacher table contains all the preacher details and sermons table contains sermons of all preachers. Am using pagination for displaying preachers(2/page). if the value of site_settings table is 1 or 2 then no of preachers will display 2, if 3 or 4 then preachers 4... I don't know what is happening. Is it a problem with pagination or limit? I am using the following code for this ( In Model)
Method in Model
function viewAll($offset=0, $limit=null) {
$this->db->select('settings_value');
$this->db->from('site_settings');
$this->db->where('settings_name', 'preachercount');
$count = $this->db->get()->row();
echo $count->settings_value;
$preacher = array();
$this->db->select('preacher.preacher_id,preacher.first_name,preacher.last_name,preacher.preacher_image,preacher.preacher_logo,preacher.preacher_bio_brief');
$this->db->distinct('preacher.preacher_id');
$this->db->from('preacher');
$this->db->join('sermons', 'sermons.preacher_id=preacher.preacher_id');
$this->db->order_by('preacher.sort_order');
$this->db->limit($count->settings_value);
$query = $this->db->get('', $limit, $offset);
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$preacher[$row->preacher_id]['preacher_id'] = $row->preacher_id;
$preacher[$row->preacher_id]['preacher_name'] = $row->first_name . ' ' . $row->last_name;
$preacher[$row->preacher_id]['preacher_image'] = $row->preacher_image;
$preacher[$row->preacher_id]['preacher_logo'] = $row->preacher_logo;
$preacher[$row->preacher_id]['preacher_bio_brief'] = $row->preacher_bio_brief;
$this->db->select('*');
$this->db->from('sermons');
$this->db->where('preacher_id', $row->preacher_id);
$this->db->order_by('sort_order ');
$sermon_array = array();
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row1) {
$sermon_array[$row1->sermon_id] ['sermon_image'] = $row1->sermon_image;
$sermon_array[$row1->sermon_id] ['sermon_title'] = $row1->sermon_title;
$sermon_array[$row1->sermon_id] ['audio_file'] = $row1->audio_file;
$sermon_array[$row1->sermon_id] ['sermon_description'] = $row1->sermon_description;
}
}
$preacher[$row->preacher_id]['sermon'] = $sermon_array;
}
return $preacher;
}
return false;
}
Method in controller
function list() {
$paginate_segment = $this->uri->segment(3) ? $this->uri->segment(3) : 0;
$winner_list = $this->sermon_model->viewAllpreachers(0, null);
$config['base_url'] = base_url() . 'sermons/index/';
$config['total_rows'] = ($winner_list) ? count($winner_list) : 0;
$config['per_page'] = 2;
$config['full_tag_open'] = '';
$config['full_tag_close'] = '';
$config['uri_segment'] = 3;
$config['num_links'] = 4;
$config['display_pages'] = TRUE;
$config['first_link'] = 'First';
$config['first_link'] = 'First';
$config['first_tag_open'] = '<div>';
$config['first_tag_close'] = '</div>';
$config['last_link'] = 'Last';
$config['next_link'] = 'Next';
$config['prev_link'] = 'Prev';
$config['cur_tag_close'] = ' | ';
$config['num_tag_close'] = ' | ';
//initialize pagination
$this->pagination->initialize($config);
$this->data['preachers'] = $this->sermon_model->viewAllpreachers($paginate_segment, $config['per_page']);
$this->data['links'] = $this->pagination->create_links();
$this->data['page'] = $this->config->item('APP_template_dir') . 'site/home/sermons_view';
$this->load->vars($this->data);
$this->load->view($this->_container);
}
As stated in the comments, you're using a limit twice and need to combine those methods:
function viewAll($offset=0, $limit=null) {
$this->db->select('settings_value');
$this->db->from('site_settings');
$this->db->where('settings_name', 'preachercount');
$count = $this->db->get()->row();
// now use value of [$count] if [$limit] is null - else use [$limit]
$limit = (is_null($limit)) ? $count : $limit ;
$preacher = array();
$this->db->select('...');
$this->db->distinct('preacher.preacher_id');
$this->db->from('preacher');
$this->db->join('sermons', 'sermons.preacher_id=preacher.preacher_id');
$this->db->order_by('preacher.sort_order');
// then remove the [limit()] call
// $this->db->limit($count->settings_value); <-- NOT NEEDED
$query = $this->db->get('', $limit, $offset);
This effectively allows you to pass a $limit to the method, or use the settings from the db.

Resources