I am having trouble setting up pagination on codeigniter when I pass parameters in the URL
if my url is like this : search/?type=groups
what should be my $config['base_url'] for pagination to work?
if i set the base url to search/?type=groups the resulting url is search/?type=groups/10
which means $_GET['type']=groups/10
thank you
In pagination config:
if (count($_GET) > 0) $config['suffix'] = '?' . http_build_query($_GET, '', "&");
Your current $_GET vars will be shown in pagination links.
You can replace $_GET by another associative array.
This won't add a query string unless one already exists.
Update:
I just saw, if you go back from another pagination number to click on the first(1), CI does not care anymore of your suffix config.
To fix that use $config['first_url'].
e.g: $config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
The most up-to-date answer of this question is;
You should enable the reusage of the query string by enabling this configuration:
$config['reuse_query_string'] = true;
after that you should initialize the pagination:
$this->pagination->initialize($config);
Added $config['reuse_query_string'] to allow automatic repopulation
of query string arguments, combined with normal URI segments. - CodeIgniter 3.0.0 Change Log
Here is my jquery solution:
Just wrap pagination links in a div like this:
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';
than add the following jquery code:
$("#pagination > a").each(function() {
var g = window.location.href.slice(window.location.href.indexOf('?'));
var href = $(this).attr('href');
$(this).attr('href', href+g);
});
Works fine for me.
if you are using codeigniter 2 there's an option in config.php, $config['allow_get_array'] - make sure its on TRUE.
Then set the pagination option $config['page_query_string'] to TRUE.
And finally, in your case set $config['base_url'] to "search/?type=groups", the pagination will append the per_page query string after it.
It should work this way, you'll get the offset in $this->input->get("per_page").
code strong!
I struggled with the same issue today. My solution is this:
Generate the pagination links and store them in a string ( $pagination = $this->pagination->create_links(); )
Use regexp to find all links and add query strings
The regular expression code used is:
<?php
$query = '?myvar=myvalue';
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
$unique = array();
if( preg_match_all("/$regexp/siU", $pagination, $matches) )
{
foreach ( $matches[2] as $link )
{
if ( !isset($unique[$link]) )
{
$data['pagination'] = str_replace($link . '"', $link . $query . '"', $data['pagination']);
$unique[$link] = '';
}
}
}
unset($unique);
Works like a charm for me! What it does is:
Find all links
Replace unique links (since there is a previous/next links same link may appear more than once) with the original link and the query-string.
Then just assign the variable to the template that will be shown and use print $your_pagination_variable_name; to show the links with your query-strings attached!
I think you are trying to do the same thing I was trying to do and I got it to work correctly by not setting a base url and just using this setup it kept me from having to manually editting the library
$this->load->library('pagination');
$config['use_page_numbers'] = TRUE;
$config['page_query_string'] = TRUE;
$config['total_rows'] = 200;
$config['per_page'] = 20;
$this->pagination->initialize($config);
Using the $config['suffix'] is the IMO best way to implement this because it doesn't require any extra processing as the regex solution. $config['suffix'] is used in the rendering of the urls in the create_links function that's part of the system/libraries/Pagination.php file so if you set the value it'll be used in the generation of the urls and won't require anymore processing which means it'll be faster.
Thanks for the post, this saved me tons of extra, not needed, coding!
Before line:
$this->base_url = rtrim($this->base_url).'&'.$this->query_string_segment.'=';
Replace this code below:
if(isset($_GET[$this->query_string_segment]))
{
unset($_GET[$this->query_string_segment]);
}
$uri = http_build_query($_GET);
$uri = empty($uri) ? '?' : $uri . '&';
$this->base_url = rtrim($this->base_url).$uri.$this->query_string_segment.'=';
Just see this link.
Just update the modified pagination class and then add
$config['get'] = "?string=" . $_REQUEST['string']."&searchBy=" . $_REQUEST['searchBy'];
The solution is that CodeIgniter does not function like that.
what I need is a method ( in the controller ) for each one of the options in "type"
so one option would be a method called :groups , another called entries etc etc
each method refers to a different model class or method as needed.
I am trying to better understand OOP and CI ...a bit of adjusting to do ... feel free to comment and correct me if i am wrong.
thank you
I got the same problem. My solution is to modify Pagination and put it in application/libraries.
First i create
var $get='';
and find all "a" elements and add $get in the href="........'.$this->get.'"'>.......</a>
Now in the controller or model input these line
$config['get']=(isset($_GET['search']))?'?search='.$_GET['search']:'';
That's it! i hope it will help you.
IN YOUR CONTROLLER:
$config['anchor_class'] = "class='link-pagination'";
IN YOUR VIEW:
$(".link-pagination").each(function() {
$(this).attr("href", $(this).attr('href') + "?id=<?= $this->input->get('id') ?>");
});
Had the same problem but realized that newer versions of CI have a suffix defined within the pagination class. Though it's still not in the documentation. No need to hack it.
I have encountered with similar kind of problem, and based on the above answer here is what I have to do for customization according to my needs.
My URI was to be something like this:
base_url() . /search/?term=
So, here is what I have done:
$config['base_url'] = base_url ."/search/?term=" . $_GET['term']
Hope you'll find the answer on this page:
LINK. Edit your answer back in if you can.
Related
may not have explained this properly but here we go.
I have a URL that looks like http://www.test.co.uk/?page=2&area[]=thing&area[]=thing2
Multiple "area"s can be added or removed from the URL via links on the site. on each addition of n "area" I wanted to remove the "page" part of the URL. so it can be reset to page1. I used parse_url to take that bit out.
Then I built an http query so it could generate the URL properly without "page"
this resulted in "area%5B0%5D=" "area%5B1%5D=" instead of "area[]="
When I use urldecode, now it shows "area[0]=" and "area[1]="
I need it to be "[]" because when using a link to remove an area, it checks for the "[]=" - when it's [0] it doesn't recognise it. How do I keep it as "[]="?
See code below.
$currentURL = currentURL();
$parts = parse_url($currentURL);
parse_str($parts['query'], $query);
unset($query['page']);
$currenturlfinal = http_build_query($query);
urldecode($currenturlfinal);
$currentURL = "?" . urldecode($currenturlfinal);
This is what I've done so far - it fixes the visual part in the URL - however I don't think I've solved anything as I've realised that what represents 'area' and 'thing' is not recognised as $key or $val as a result of what I think is parsing or reencoding the url in accordance with the code below. So I still can't remove 'areas' using the links
$currentURL_with_QS2 = currentURL();
$parts = parse_url($currentURL_with_QS2);
parse_str($parts['query'], $query);
unset($query['page']);
$currenturlfinal = http_build_query($query);
$currenturlfinal = preg_replace('/%5B[0-9]+%5D/simU', '[]', $currenturlfinal);
urldecode($currenturlfinal);
$currentURL_with_QS = "?" . $currenturlfinal;
$numQueries = count(explode('&', $_SERVER['QUERY_STRING']));
$get = $_GET;
if (activeCat($val)) { // if this category is already set
$searchString = $key . '[]= ' . $val; // we build the query string to remove
I'm using Wordpress as well may I add - maybe there's a way to reset the pagination through Wordpress. of course even then - when I go to page 2 on any page it still changes the "[]" to "5b0%5d" etc....
EDIT: this is all part of a function that refers to $key (the area/category) and $val (name of area or category) which is echoed in the link itself
EDIT2: It works now!
I don't know why but I had to use the original code and make the adjustments I did before again and now it works exactly how I want it to! Yet I couldn't see any visible differences in both codes afterwards. Strange...
As far as I know, there is no built-in way to do this.
You could try with:
$currenturlfinal = http_build_query($query);
Where $query is querystring part w/o area parameters and then:
foreach ($areas as $area) {
$currenturlfinal .= '&area[]='.$area;
}
UPD:
you could try with:
$query = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);
just place it right after http_build_query call.
This is the code i currently have.
P.S. I am currently editing this, trying to solve this problem whilst waiting for someone to solve it here. Im not quite sure why this is happening.
Pagination:
$character = $this->uri->segment(3);
$config['base_url'] = base_url() . 'index.php/Controller/function/'.$character;
$config['total_rows'] = $this->Model->browse_total_rows();
$config['per_page'] = 1;
$config['num_links'] = 10;
$config['uri_segment'] = 4;
$this->pagination->initialize($config);
if(!is_numeric($character)){$data['records'] = $this->Model->get_records_filtered($character,$config['per_page'],$this->uri->segment(4));}
else{ $data['records'] = $this->Model->get_records($config['per_page'], $this->uri->segment(3));}
$data['links'] = $this->pagination->create_links();
$this->load->view('browse', $data);
Whenever i go to my browse page, instead of being on the page 1 of my page on pagination. it is defaulted that im on page 2. Why? because i see this as my link.
1 2 3 >
Plus, i can't click on link 2 but i can on link 1. I don't know if this is how pagination_links works. but i find it odd. Anyways, im not sure if its related to my other problem.
The character part is for the letter chosen, so for example i only want to view results with A as their first letter the url should be.
index.php/controller/function/A/
So the per page of the pagination will be placed on the 4th segment. It has no error that way. But when i don't click on any letter and just show all results.
Whenever i click on a link(per page). The url looks like this.
index.php/controller/function/2/
but when i click on the next page, it goes as
index.php/controller/function/2/4
so basically breaks the pagination and retrieves no result.
I have tried other solutions like adding IF/else statement that if character is null or not equal to range('A','Z') then the $config['base_url'] should have no .$character on the end and the uri_segment should be on 3rd. But it still goes the same as above.
EDIT:
The 2nd problem was solved, i used something like this.
$character = $this->uri->segment(3);
$Alphabet = range('A','Z');
$flag = 0;
for($i=0;$i<26;$i++)
{
if($character==$Alphabet[$i])
{
$flag +=1;
}
}
Seems like, if($character==range('A','Z')) doesnt work as only now noticed when i echoed that range returns results of array so i had to loop. is there any better way to check than what ive done above?
With your pagination config, you have the pagination segment set to 4 regardless of the whether a letter is specified or not. But it should be 3 when there is no character if I'm understanding correctly.
Try something like this:
if(!is_numeric($character)) {
$config['uri_segment'] = 4;
$data['records'] = $this->Model->get_records_filtered($character,$config['per_page'],$this->uri->segment(4));
} else {
$config['uri_segment'] = 3;
$data['records'] = $this->Model->get_records($config['per_page'], $this->uri->segment(3));
}
$this->pagination->initialize($config);
For checking for a character in the range, you can use
if (in_array(strtoupper($character), range('A', 'Z'))
The strtoupper() is optional. Leave it in if you want 'a' to match 'A'.
I'm having problems in adding additional link segments at the end of each page number. For instance, I set the config of pagination to:
$config['base_url'] = site_url() . 'admin/employee/search/';
Now, each of the links may contain page numbers but I also want to include the search term.
Instead of having links like: 'mysite/admin/employee/search/1..2..3' on paginated numbers,
I want to have like this: 'mysite/admin/employee/search/mysearchterm/1..2..3'.
How would I do it?
Try this:
if($this->uri->segment(3)){
$keyword = $this->uri->segment(3);
}
else if($this->input->get('keyword')){
$keyword = $this->input->get('keyword');
}
$config['base_url'] = base_url().'home/paginate_search/'.$keyword.'/page/';
I’ve tried for some time now to solve what probably is a small issue but I just can’t seem get my head around it. I’ve tried some different approaches, some found at SO but none has worked yet.
The problem consists of this:
I’ve a show-room page where I show some cloth. On each single item of cloth there is four “views”
Male
Female
Front
Back
Now, the users can filter this by either viewing the male or female model but they can also filter by viewing front or back of both gender.
I’ve created my script so it detects the URL query and display the correct data but my problem is to “build” the URL correctly.
When firstly enter the page, the four links is like this:
example.com?gender=male
example.com?gender=female
example.com?site=front
example.com?site=back
This work because it’s the “default” view (the default view is set to gender=male && site=front) in the model.
But if I choose to view ?gender=female the users should be able to filter it once more by adding &site=back so the complete URL would be: example.com?gender=female&site=back
And if I then press the link to see gender=male it should still keep the URL parameter &site=back.
What I’ve achived so far is to append the parameters to the existing URL but this result in URL strings like: example.com?gender=male&site=front&gender=female and so on…
I’ve tried but to use the parse_url function, the http_build_query($parms) method and to make my “own” function that checks for existing parameters but it does not work.
My latest try was this:
_setURL(‘http://example.com?gender=male’, ‘site’, ‘back’);
function _setURL($url, $key, $value) {
$separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&';
$query = $key."=".$value;
$url .= $separator . $query;
var_dump($url); exit;
}
This function works unless the $_GET parameter already exists and thus should be replaced and not added.
I’m not sure if there is some “best practice” to solve this and as I said I’ve looked at a lot of answers on SO but none which was spot on my issue.
I hope I’ve explained myself otherwise please let me know and I’ll elaborate.
Any help or advice would be appreciated
You can generate the links dynamically using the following method:
$frontLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=front':'mydomain.com?site=front';
$backLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=back':'mydomain.com?site=back';
This is a 1 line if statement which will set the value of the variables $frontLink and $backlink respectively. The syntax for a 1 line if statement is $var = (if_statement) ? true_result:false_result; this will set the value of $var to the true_result or false_result depending on the return value of the if statement.
You can then do the same for the genders:
$maleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=male&site='.$_GET['site']:'mydomain.com?gender=male';
$femaleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=female&site='.$_GET['site']:'mydomain.com?gender=female';
Found this by searching for a better solution then mine and found this ugly one (That we see a lot on the web), so here is my solution :
function add_get_parameter($arg, $value)
{
$_GET[$arg] = $value;
return "?" . http_build_query($_GET);
}
<?php
function requestUriAddGetParams(array $params)
{
$parseRes=parse_url($_REQUEST['REQUEST_URI']);
$params=array_merge($_GET, $params);
return $parseRes['path'].'?'.http_build_query($params);
}
?>
if(isset($_GET['diagid']) && $_GET['diagid']!='') {
$repParam = "&diagid=".$_GET['diagid'];
$params = str_replace($repParam, "", $_SERVER['REQUEST_URI']);
$url = "http://".$_SERVER['HTTP_HOST'].$params."&diagid=".$ID;
}
else $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."&diagid=".$ID;
I am a bit new to the routing with CI, and I don't understand it quite well (to be honest not at all). I have following url which need to be changed:
domain.com/mali_oglasi/index/1(some number)
It is used for pagination, and I need it to be shorten to:
domain.com/mali_oglasi
I tried:
$route['mali_oglasi/index/(:num)'] = 'mali_oglasi';
but it doesn't seems to work(nothing is changed). What am I doing wrong, what needs to be changed?
Index function from the controller mali_oglasi:
function index() {
$config['base_url'] = base_url().'mali_oglasi/index';
$config['total_rows'] = $this->db->count_all('ad');
$config['per_page'] = 10;
$this->pagination->initialize($config);
$data['pagination_links'] = $this->pagination->create_links();
$data['title'] = "Mali Oglasi | 010";
$data['oglasi'] = $this->mgl->mgl_get_all_home($config['per_page']);
$data['loc'] = $this->gi_loc;
$data['cat'] = $this->gi_cat;
$data['stylesheet'] = $this->css;
$data['main_content'] = 'mali_oglasi';
$this->load->view('template',$data);
}
You need to use .htaccess for what you are trying to achieve, more importantly, the "mod_rewrite" part:
https://www.google.co.uk/search?q=htaccess+rewrite
CodeIgniter routing doesn't change the look of the URL, it simply changes it's destination.
Codeignitor routing is simple as
serverpath(base_url)/controller/method(function)/para1/valu1/para2/valu2...
you hide index file from defining .htaccess rule(creating file).
more info please visit : user_guide in Easily you are understand.
Try:
$route['mali_oglasi/(:num)'] = 'mali_oglasi/index/$1';
Your domain.com/mali_oglasi/index/1 can then be accessed at domain.com/mali_oglasi/1
Edit:
To loose the /1 just do:
$route['mali_oglasi'] = 'mali_oglasi/index/1';
try this
$route['mali_oglasi/(:num)'] = 'mali_oglasi/index/$1';
it will help you
http://codeigniter.com/user_guide/general/routing.html
and for pagination you can add this
$config['uri_segment'] = 3;
its optional but better to add