2

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())
);
0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.