Generate URL in Symfony 5 with GET parameters - php

In Symfony 5, I would like to generate an URL partially based on GET paramaters already posted.
Let's assume that the URL posted is:
user/edit/5?foo=1&bar=1&baz=1&qux=1
I would like to generate in the controller without foo:
user/edit/5?bar=1&baz=1&qux=1
First, I remove foo parameter :
$request->query->remove('foo');
If I didn't get the user_id in the URL as route parameter (5), I would use:
$this->generateUrl('user_edit', $request->query->all());
But this is not working because user_id is missing. So how can I generated such URL without rewriting all variables:
$this->generateUrl('user_edit', ['id' => $user->getId(), ???]);
I was thinking about PHP function array_merge() but this seems to me more a trick than an elegant solution:
$this->generateUrl('user_edit', array_merge(
['id' => $user->getId()],
$request->query->all())
);

There is nothing wrong in using array_merge(). That's exactly what you want to accomplish. It's not a "trick", it's a language feature.
If you want a less verbose syntax, just use +.
$this->generateUrl('user_edit', $request->query->all() + ['id' => $user->getId()]);
The end result is exactly the same for the above, and it's shorter.

Related

Laravel Paginator's "append" generates different key for array

Using Laravel 5.5 with PHP 7.0, trying to create and append some queries to pagination following the docs.
https://laravel.com/docs/5.5/pagination#displaying-pagination-results
However with some queries which have multiple values, rendered links have different keys.
Simplest reproducing code is:
>>> User::query()->paginate(30)->appends(['query' => ['foo', 'bar', 'baz']])->nextPageUrl()
=> "http://homestead.app?query%5B0%5D=foo&query%5B1%5D=bar&query%5B2%5D=baz&page=2"
# expecting "http://homestead.app?query%5B%5D=foo&query%5B%5D=bar&query%5B2%5D=baz&page=2"
In other words, the next url of /user?page=1&query[]=1&query[]=2 should be:
/user?page=2&query[]=1&query[]=2
but actually
/user?page=2&query[0]=1&query[1]=2
What is wrong in my code?

generating url parameters from array

Let's say I have the following array :
$params
= array(
'foo' => 'bar',
'baz' => array('qux', 'qux2', 'qux3')
);
is there a pre-built function in php so :
the_function($params);
outputs
'foo=bar&baz[]=qux&baz[]=qux2&baz[]=qux3'
?
Note : i am asking for a pre-built function, I can code the function myself. Just making sure I am not coding something already existing.
How come nobody suggested this before. http_build_query() is what you were looking for.
$params = array('foo'=>'bar','baz'=>array('qux','qux2','qux3'));
echo urldecode(http_build_query($params));
// foo=bar&baz[0]=qux&baz[1]=qux2&baz[2]=qux3
A few caveats you might have to be aware of :
the resulting string is urlencoded (use urldecode() as I did above if necesary)
array indexes are present in the query string
Some of the comments in the documentation page can help with the latter if needed. http://php.net/manual/en/function.http-build-query.php

Calling an Array through URL

I'm looking to call an array through a URL, and I have looked through the questions but from what I've seen they're all for creating a url from an array/something of that sort.
I'm a bit new to HTML and such, but I can read and understand a decent amount. What I'm trying to do is make a shortcut on a website that allows me to call an array through the URL.
I get an error saying I can either use an int or an array, but I haven't found if I need a certain value in the url or I'm just calling the array the wrong way. I know how to make one in java/javascript and C++, as well as calling via code, but not through URL like it's saying I can.
Reason I'm looking to do this is get something done at a faster pace, and all at once instead of one by one. I'm using Google Chrome, and the website uses yuigen, as well as javascript, but the URL doesn't direct anything through PHP thatI know of.
Based on your comments, you want to take a URL like this:
http://this.com/?thisArray=1|2|5|6|10|5
and get an array of the values in thisArray. Just do this:
$theArray = explode('|', $_GET['thisArray']);
// now, $theArray is a PHP array: [1, 2, 5, 6, 10, 5]
$_GET['thisArray'] accesses your URL parameter, and explode('|', ...) splits it on the pipes.

ToroPHP routing - URL rewrite with childs

I'm using PHP and ToroPHP for routing.
Unknown number of child pages
It works fine, but in my case I can add pages with childs and parents, where a parent can have an unknown number of have childpages.
In ToroPHP it might look like this:
// My Path: http://www.test.com/product/house/room/table/leg/color/
Toro::serve(array(
"/" => "Home",
"/:string/:string/:string/:string/:string/:string/" => "Page"
));
class Page {
function get($slug, $slug2, $slug3, $slug4, $slug5, $slug6) {
echo "First slug: $slug";
}
}
Problem
I can figure out what the maximum depth can be and then loop and append
out a string containing the "/:string" parameters but it don't look
that nice.
The get-function in the Page-class takes an unknown number of in
parameters. I can calculate the max depth from outside the function, but I need the function to know how many values to take.
Question
Is there an alternative way the the problem 1? Some regular expression maybe?
How can I make a function take an unkown number of in parameters?
Maybe I try to solve this the wrong way and the first two questions are not relevant? Correct me if that is.
In order for your action to receive all parameters, you need to capture them in your regex. You capture a value in regular expressions using parentheses. :string is just an alias for ([a-zA-Z]+). You could apply a wildcard after the first segment, like this:
"/product/(.*?)" => "Page"
However, this means that you need to parse the URL by yourself in your action, which is not very clean either.
If you want to make this particular case more clean, an option would be to use str_repeat:
Toro::serve(array(
"/" => "Home",
"/" . str_repeat(":string/", 6) => "Page"
));
ToroPHP is a very simple library, it should not be that hard to fork it and bend it to your will. Ideally, how would you like to define routes like this? Maybe a route like /:string*6?
You can always pass more or fewer parameters than defined to a PHP function. Use func_get_args to get all passed parameters and func_num_args to get the number of passed parameters.
In response to question 2, can you possibly format the GET parameters into an array and then pass in arrays rather than individual values?
Maybe like:
$allSlugs = array($slug, $slug2, $slug3, $slug4, $slug5, $slug6);
// Pass $allSlugs into your instance of Page::get($allSlugs);
class Page {
function get($getValues) {
echo isset($getValues[0]) ? "First slug: ".$getValues[0] : '';
}
}

Parameter after url is not passed to called function when Parameter contains : or \

I am passing keyword inputed by user to
function search_result($input)
in cakephp fron Javascript
like this www.example.com/search_result/input from Javascript
where input is from user
It gives an error when input contains : as no arguments found for search_result. It working fine for other inputs.
You will probably want to encode the search term before passing it to PHP from Javascript (which I assume means you're using AJAX).
You can do this by using:encodeURIComponent:
encodeURIComponent(term);
In addition to URI encoding, the problem is that : is used to separate cake parameters, so when you have it in your search query, cake thinks it's a param.
But, there is a fix in the book, apparently, you can use the "trailing star syntax":
Router::connect(
'/search_result/**', // notice two stars instead of one
array('controller' => 'search', 'action' => 'search_result')
);
This should pass everything after the /search_result/ as a single param.
Hope that helps.

Categories