Play Framework - Redirect with params

Go To StackoverFlow.com

14

I am trying to figure out how to do a redirect within a controller action in Play (2.0) using Scala.

The redirect using

Redirect(routes.Application.index)

works just fine.

What I cannot figure out from the docs, API, or Google is how to add parameters to the call.

I am coming from Grails where this could be done easily as follows:

redirect action: "index", params: ["key": "value"] .

The only way I have found is to call Redirect using a string url and a query string, which seems awkward.

Basically I would like to make use of Redirect(Call) somehow, but I do not how to create the Call object using reverse routing.

Am I missing something/not getting the concept in Play/Scala?

Thanks in Advance!

2012-04-04 21:20
by pchronz


16

Ellou'

A route is just a function, so you can pass arguments as usual:

// Redirect to /hello/Bob
def helloBob = Action {
    Redirect(routes.Application.hello("Bob"))    
}

This snippet comes from http://www.playframework.org/documentation/2.0/ScalaRouting (at the bottom)

2012-04-04 21:38
by biesior
Thanks! Actually, I tried this in the first place, but the compiler complained, that I entered too many arguments. The problem was: the action takes a Long, but in the Routing I defined, that there should be a default value for the action. I had to remove that. So now I need to call either index(None) or index(Some(foo)). Coming from Grails this seems really tedious - pchronz 2012-04-04 23:10
+1 This is what type-safe URLs are all about. I wish play would sell them more for what they are - Dan Burton 2012-04-04 23:16
+1 as well for type-safe, @DanBurton, thanx for edit - biesior 2012-04-05 08:14
Has this changed in recent play? I can't seem to find/import routes (I get value routes is not defined) - Andy Hayden 2015-09-22 17:40


0

You can also avoid creating another function just for this in your controller. In your route config, you can simply add something like this:

  GET  /google  @controllers.Default.redirect(to = "http://google.com")
2015-03-01 06:37
by Yawo Guillaume Kpotufe
@zenith: hope it help - Yawo Guillaume Kpotufe 2015-03-22 09:19
Muuuuch better - emlai 2015-03-22 09:21
This doesn't seem to work. I get No such file or directoryAndy Hayden 2016-07-25 22:57
Ads