39

How can I redirect to another action passing 2 or more parameters?

This code:

$this->redirect('input/new?year=' . $year . '&month=' . $month);

Results in URL:

http://.../input?year=2009&month=9

6 Answers 6

58

Well, that's normal, "redirect" redirect to an absolute URL. You can do that:

$this->redirect($this->generateUrl('default', array('module' => 'input',
'action' => 'new', 'year' => $year, 'month' => $month)));
Sign up to request clarification or add additional context in comments.

3 Comments

that helped. except for it generates url like "http://.../input/new/year/2009/month/10"
If you have a route defined, you can replace 'default' by its name, and change the second parameter with the routes's parameters, if needed.
If you have a route defined, you can actually use $this->redirectToRoute('routename', ['param1' => 'value', ['param2' => 'value'])
11

In the currently supported Symfony versions (2.7+) it's even easier (plus, you can optionally add also the status code at the end):

return $this->redirectToRoute(
    'default',
    array('year' => $year, 'month' => $month),
    Response::HTTP_MOVED_PERMANENTLY // = 301
);

Comments

5

You can also use redirect, specifying the route name and the parameter array:

$this->redirect('route_name', array('year' => $year, 'month' => $month));

(Tested on Symfony 1.4)

Comments

3

I think this is no normal symfony behavior. Have you defined some routing rules?

Have you also tried this:

$this->redirect('module/action?'.http_build_query($paramsArray));

Comments

1

Strange thing. Does

$this->redirect('@default?module=input&action=new&year=' . $year . '&month=' . $month);

work for you?

1 Comment

yes, that also work. thanks, but xarch's solution is prettier =)
-4
$this->redirect('input/new/year/' . $year . '/month/' . $month);

3 Comments

this undermine the internal routing system of symfony
it actually doesn't. symfony's intelligent internal routing engine is exactly why this redirect works! but thanks for the down vote ;)
when you do it this way you have to change all links/redirects when adjusting the according routing rule

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.