Reputation: 819
I am trying to send dynamic values to the Routes URI path based on the content of a textbox but when I tried, it is coming as null.
This is what I tried:
<form action="@{Application.hello(myName)}" method="get">
Name: <input type="text" name="myName">
<input type="submit" value="Submit">
</form>
I want the value entered in the textbox to be passed to the routes file but its not working. If I pass a constant string such as:
<form action="@{Application.hello('John')}" method="get">
Name: <input type="text" name="myName">
<input type="submit" value="Submit">
</form>
Then my code is working fine but I dont want an constant value; I want the textbox value to be passed in the routes URI path.
EDIT
With the above code, every time when the button is clicked and the form is submitted, the URL will contain the name as /.../John
since I have hardcoded it.
What I want to achieve is not to hardcode the name to John
. The name in the URL will come from the entry made by the user in the textbox. e.g. If the name entered by the user is Mike
then the URL should be /.../Mike
and so on based on the user textbox input.
In simple words, I don't want to hardcode the value to John
but willing to make it dynamic based on the textbox input.
Please let me know how to do this.
Regards,
Upvotes: 1
Views: 1432
Reputation: 396
You are trying to route to a URL for a user name that has yet to be specified.
On page load, Play doesn't know you want hello /name/John when the user hasn't specified John as the name.
In order for you do something like you want to do, you would want to use javascript to change the form action url upon submit to replace the action url with /name/(value of myName input field)
Alternatively, you can split this up to two separate controller actions.
routes:
POST /greet Application.greet
GET /users/{myName} Application.hello
Application.java
// accepts the form request with the myName paramater
public static void greet(String myName) {
// redirects the user to /users/{myName}
Application.hello(myName);
}
// welcomes the user by name
public static void hello(String myName) {
render(myName);
}
view template:
<-- this url should be /greet (noted we are submitting via POST) -->
<form action="@{Application.greet()}" method="post">
Name: <input type="text" name="myName">
<input type="submit" value="Submit">
</form>
Upvotes: 1