I'm trying to implement a displayPerPage (10, 25, 50, etc.) when displaying a list of results on an index page. However i'm having a hard time how to just append that to the url without replacing the other query strings.
Example:
I have a paginator to switch pages however, if i'm on page 5 for example and select display per page 10 results on my select dropdown, it will load the results but erase the page=5 from the url. How to I just append displayPerPage without erasing where I currently am on the paginator.
Thanks for any help.
I know its possible to do it without creating a custom paginator since I have done it on another project with laravel 4, but that was a while back and I can't seem to figure out how to do it again.
Assuming $objects is the list of the item you're paginating, on your view you can add your paginator like that:
{{$objects->appends(request()->query())->links()}}
and query strings like your requestPerPage will be carried
After battling with this issue, I wrote a url parser helper function in php to to find and replace certain things in url after the ? sign (query part)
//for displayPerPage, orderBy and sortBy parse the url and replace with new values
function urlQueryParse($queryToReplace, $newValue){
// extract query from url
$fullUrl = Request::fullUrl();
if(strpos($fullUrl, '?') !== false){
//find everything after the ? in url
$url = substr($fullUrl, strpos($fullUrl, "?") + 1);
// check url to make sure $queryToReplace exists in the url
if(strpos($url, $queryToReplace) !== false) {
// look through the remaining url query and replace whats given to the function
$newUrL = preg_replace('/('. $queryToReplace. '\=)([^&]+)/', $queryToReplace.'='.$newValue, $url);
return Request::url()."?{$newUrL}";
}
// if the ? exists but the queryToReplace is not in the url, then add it to the query string
return Request::url()."?{$url}&{$queryToReplace}={$newValue}";
}
//if the url doesnt have ? sign then simply insert the new value
return Request::url()."?{$queryToReplace}={$newValue}";
}
Hopefully this helps someone. If you have any ides of how to improve it, I'm open to suggestions.
P.S. I'm working on Laravel 5.2
Related
In behat I would like to check to see if the route I am going to is the correct route, the only issue is everytime I visit the route the number changes. How would I set up my behat to look for any number after wards and let it pass. So what I have is:
Then I should be on "/clinic/participant/create/{id}"
That bracket {id} will always be dynamic and if possible I would like to either ignore the last id or put a wildcard of some sort on it to say whatever is passed here works as long as its a number.
This is my work around, but I would still like to know if there is a easier way / cleaner way to do this.
public function iShouldBeOnRoute($url)
{
$urlArray = explode('/', $url);
$urlPath = $this->getSession()->getCurrentUrl();
$urlPathArray = explode('/', $urlPath);
$testedUrl = join('/', $urlArray) . end($urlPathArray);
$this->assertSession()->addressEquals($testedUrl);
}
Assuming that this URL is an existing link that you can actually see, then you could create a custom step that gets the href attribute and then visit that url.
For example:
I am on create participant page
this step should contain:
- find element -> get attribute href, save it in a variable
- use visit with that variable
The css selector used should be:
a[href*='/clinic/participant/create/']
If you have the id and you only need to check that the url contains that id you could just use a strpos !== false and throw exception or an assert.
I have on website a part which is at the moment hidden. I have also a few requests on query string ?visible=true. How can i add this query string automatic to every url if in url is this querystring available ?visible=true? This is simple method where i enable hidden parts of website.
If i understand you correctly, you mean your page loads with various parameters and your wanting to have the next page load with any existing parameters as well as any that you want to add along with them.?
Example: somepage.html?visible=true&showmenu=5
Then you want to add "anotheropt=helloworld"
Example: somepage.html?visible=true&showmenu=5&anotheropt=helloworld
To do something like this, you have a few different options depending on what resources you have available...
Javascript / Client Side:
Use a function to get all the parameters from the current url Something Like This
Loop over all of them and build a new string with the ones you want to keep
Add your own to the end of the string
Note the above link only retrieves them by name, you would want to simple do a split/explode type operation on the string and them perform your own logic to which items you want.
PHP / Server Side:
Same deal, loop or something to get all of the current ones $_GET should do...
Echo these into a hidden input box and append them to the end of new links..
Note you still need to filter your parameters to choose what to keep and what to ignore.
Further more, it would not be hard to write or find a function that will merge two arrays or perform a comparison.
OR
Is it as simple as this below??
var x = location.search;
var sl = "mypage.html" + x + "&someoption=helloworld"
OR THIS
<?php
if (isset($_GET['visible']) && $_GET['visible']=='true') {
echo "SHOW ME, i was a hidden element";
} else {
// NOTHING, VISIBLE IS NOT TRUE OR NOT SET...
}
?>
Your home page is accessed without ?visible=true. So you have add it at-least once. When you make link, call some function for that:
class Link {
const BASE_URL = 'http://example.com';
public static function url($link, $visible = false) {
return self::BASE_URL."/".$link.(!empty($visible) ? '?visible=true' : '');
}
}
I have small problem.
I've coded a full website in php using CodeIgniter framework. One of my modules is search module, it contains text input with keyword and three select lists with filtering criterias.
That's ok, when I'm searching something - result's listing pagination is done via URL like that:
mysite.com/$keyword/$criteria1/$criteria2/$criteria3/$offset
works like a charm.
But when I'm entering into one of my images (it's image gallery) I want to have an option to go into NEXT and PREVIOUS image from my search results - the ones which I entered this image from.
I'm solving this case now in this way - I have session table called 'search_conditions' and I'm storing values of keyword and my three criterias there, but that's quite not comfortable, because why if someone opens second window and search something else there?
Then all of his searches in another windows or tabs are getting the same criteria - because with every new search, user overwrite the session value.
My next and previous functions:
public function next($count)
{
$search = $this->session->userdata('search_conditions'); //getting session table and overwriting it
$catid = isset($search['catid'])?$search['catid']:'0';
$brandid = isset($search['brandid'])?$search['brandid']:'0';
$prodid = isset($search['prodid'])?$search['prodid']:'0';
$keyword = isset($search['keyword'])?$search['keyword']:'';
$res = $this->search_model->main_search($keyword, $catid, $brandid, $prodid, $count, 1);
}
public function previous($count)
{
$search = $this->session->userdata('search_conditions');
$catid = isset($search['catid'])?$search['catid']:'0';
$brandid = isset($search['brandid'])?$search['brandid']:'0';
$prodid = isset($search['prodid'])?$search['prodid']:'0';
$keyword = isset($search['keyword'])?$search['keyword']:'';
$res = $this->search_model->main_search($keyword, $catid, $brandid, $prodid, $count-2, 1);
}
Can you recommend me some other, more comfortable solution, because this seems not to be good...
: )
Thank you!
Add an index to the $search_conditions variable:
$search_conditions[1]['catid']
$search_conditions[1]['brandid']
...
then refer to it with a controller's or config variable. This way you can allow one session to store multiple search conditions.
But I would recommend you drop storing the search condition in session. Instead, just pass it with the URI. Session data, in the case you describe, work as an intermediary; you don't need it. Use the Pagination Class and pass the search page number, not the direction (next or previous) to the URI.
Do not worry that the URI may look ugly - it only depends on what user searches for, and it's still friendly to share. Your only concern is if the GET string does not extend the limited length.
Pull the segments from the URI in your next() and previous() functions. Use the codeigniter URL helper. That should allow you to pass the different search criterion as variables to the next page, this would also remove your need to use the session.
I'm doing a website. There's a pagination, you click on links and they take you to the page you need, the links pass $_GET variable ( a href="?pn=2" ) and that works fine.
However when i add the category links (also contain $_GET variable
(a href="?sort=english") on the same page, which kind of sort the content on the page, and click it, the system simply overrides the url and deletes all the previous $_GET's.
For example, I'm on page 2 (http://website.com/index.php?pn=2)
and then I click this sorting link and what I'm expecting to get is this (http://website.com/index.php?pn=2&sort=english), but what I get is this:
(http://website.com/index.php?sort=english). It simply overrides the previous $_GET, instead of adding to it!
A relative URI consisting of just a query string will replace the entire existing query string. There is no way to write a URL that will add to an existing query. You have to write the complete query string that you want.
You can maintain the existing string by adding it explicitly:
href="?foo=<?php echo htmlspecialchars($_GET['foo']); ?>&bar=123"
Try using this:
$_SERVER['REQUEST_URI'];
On this link you can see examples. And on this link I have uploaded test document where you can try it yourself, it just prints out this line from above.
EDIT: Although this can help you get the current parameters in URL, I think it's not solution for you. Like Quentin said, you will have to write full link manually and maintain each parameter.
You could create a function that will iterate through your $_GET array and create a query string. Then all you would have to do is change your $_GET array and generate this query string.
Pseudocode (slash I don't really know PHP but here's a good example you should be able to follow):
function create_query_string($array) {
$kvps = array();
for ($key in $array) {
array_push($kvps, "$key=$array[$key]");
}
return "?" . implode("&", $kvps);
}
Usage:
$_GET["sort"] = "english";
$query_string = create_query_string($_GET);
You need to maintain the query parameters when you create the new links. The links on the page should be something like this:
Sort by English
The HTTP protocol is stateless -- it doesn't remember the past. You have to remind it of what the previous HTTP parameters were via PHP or other methods (cookies, etc). In your case, you need to remind it what the current page number is, as in the example above.
I have a small issue with manipulating the current URL query string to add an extra parameter at the end.
Per example, say there's a category layout for products, the URL would be:
index.php?category=3&type=5
Now, on that page I have a link for a layout that is either a table or a grid. In those URLs I currently have:
<a href="index.php?<?php echo preg_replace($array,'',$_SERVER['QUERY_STRING']); ?>&layout=grid" ...
Then, I do the same for the table href as well. Also in my array I have just:
$array = array ( '/&layout=table/', '/&layout=grid/' )
Is this the right way, or is there a better way for doing this? I'm asking because without preg_replace, it will continue adding that same layout parameter everytime it is clicked, so it will also show the previous parameter, then the next, then the next.. without removing the previous layout parameters.
Any insight on this will be much appreciated.
EDIT:
Thanks to the answers below, I have created a little function:
function buildQuery($key,$value) {
$params = $_GET;
$params[$key] = $value;
return http_build_query($params);
}
Then its only a matter off:
grid
this might seem pointless but i like to have my view / template files without the extra set vars. Im a clean freak. I might even return the 'index.php?' with it just so i can be more lazy, anyways something to play with now :)..
If you want to modify the query string, it's easier to simply modify the GET variables and rebuild the query string:
$params = $_GET;
$params['layout'] = 'new_layout';
Then:
...
Although you could also do:
...
Think about directly parsing the $_GET paramaters to build your url.
I think what you want to do is have the link going to index.php with all the same parameters as you have at the moment, but changing layout to grid. I'd suggest you do something like this:
<?php
// make a copy of the $_GET array with all the parameters from the query string
$params = $_GET;
// set layout=grid regardless of whether layout was set before or its value
$params['layout'] = 'grid';
// generate a query string to append to your urls.
// Note that & is used as the arg separator; this is necessary for XHTML and advised for HTML
$queryString = http_build_query($params, '', '&');
?>
href="index.php?<?php echo $queryString; ?>">
This is much easier than trying to edit and fix the $_SERVER['QUERY_STRING'] yourself.