Reputation: 311
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())
);
Upvotes: 2
Views: 2861
Reputation: 47380
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.
Upvotes: 3