Passing selected value of a select to form action

playframework-2.0, scala

Solution

Actually I think you're on the wrong side for doing that.

If the form's action has to change over the use of your 'select', it has to be done using JS. So when the form is submitted (event `submit`) you have to update the url.

This can be done easily using `javascriptRoutes`.

So you have to do several things:

1/ create the javascriptRouter (assuming your add it in `Application.scala`)

def javascriptRoutes = Action {
  Ok(
    Routes.javascriptRouter("playRoutes")(
      //accounts
      controllers.routes.javascript.Accounts.menu
    )
  ).as("text/javascript")
 }

2/ define it in your `routes` file

# Javascript routing
GET     /assets/javascripts/routes      controllers.Application.javascriptRoutes

3/ add the related javascript file import in your views, let say in `main.scala.html`

<script type="text/javascript" src="@routes.Application.javascriptRoutes"></script>

4/ add a `submit` handler to your form that does that before executing the default behavior

$("form").submit(function () {
    //this computes the correct URL giving a parameter which is the value of the selected option
    var newURl = playRoutes.controllers.Accounts.menu($("#accountNames").val()).url
    $(this).attr("action", newUrl); 
})

Notice how we've used `playRoutes` both in the controller (1) and the JS call (4).

Problem

I have a menu that I want to differ based on which account is currently selected in the system. I have a page that allows a user to select an account from an html select. When the user submits the form from the account selection page I want to call the menu method on my controller passing in the selected value so my url looks correct. Here is the existing template from the page that allows a user to select an account: ``` @helper.form(action = routes.Accounts.menu { <table> <tr> <td><select id="accountNames"> @accountNames.map { name => <option value="@name">@name</option> } </select></td> </tr> <tr> <td> <p> <input type="submit" value="Choose"> </p> </td> </tr> </table> } ``` From my routes file: ``` GET /account/:accountName/menu controllers.Accounts.menu(accountName: String) ``` How do I reference the selected value from my select (id="accountNames") and pass it into my form action?

Original source