Search code examples
javascalahttprequeststatelessplayframework-2.2

Maintaining request parameters across controller and view in Play Framework


I am using Play Framework with Java and with no prior experience with Scala. What I'm trying to achieve is to maintain request parameters (typically GET) across controller and view. More specifically, I need the view to pass the parameters sent to it by the controller (via the query string) back to the controller once it hands over control. A form is generated in the template using the form helper:

@form(routes.Application.authenticate()) 

I know I can access the current request with play.mvc.Controller.request(). I need to append the data submitted by the form to the current query string and pass it all via the URL, or, in case the form method is POST, either append the current query string to the action URL or store the parameters in hidden fields and pass them all through POST.

Is there a straightforward and clean way to ahieve this? At first I tried to pass everything via an object, but then I ran into trouble with the router, plus I couldn't figure out how to pass the data back.


Solution

  • With help from this and this I finally figured out how to generate the hidden input fields. Either of the following approaches does the job:

    @for((key, value) <- request.queryString) {
      <input type="hidden" name="@key" value="@value" />
    }
    

    Or:

    @request.queryString.map { case (key,value) =>          
      <input type="hidden" name="@key" value="@value" />
    }
    

    In case of POST, @request.queryString can be simply replaced with @request.body.asFormUrlEncoded. Since both methods return Map[String, Seq[String]], one might want to flatten the values (using @value.mkString); however, in my case the code seems to work fine as is. My ignorance about Scala prevents me from delving deeper into what's happening under the hood, but I'm guessing that in each iteration, the first element from the array is returned, which should work as far as HTTP request parameters in my application are concerned. If I ever test this with edge cases, I will update this post.