3

I'm quite new to Thymeleaf, so I'm struggling with this.

I want to pass a parameter to the controller when submitting a form, with the value of a text field.

This is my controller:

@PostMapping("/postEndpoint/{myid}")
public String pidUserSubmit(@PathVariable(value = "myid") String myid) {
    log.debug("*** MY ID: {}", myid);
    return "redirect:/someOtherPage";
}

This is how I've defined the text input:

<input id="myid" name="myid" type="text" maxlength="26" title="Please enter a valid ID" class="texter" th:value="*{myid}">

And this is what I've tried in my html file with thymeleaf:

<form name="myform" id="myform" action="#" th:action="@{/postEndpoint/__${myid}__}" method="post">

I'm getting this log: *** MY ID: null

<form name="myform" id="myform" action="#" th:action="@{/postEndpoint/${myid}}" method="post">

I'm getting this log: *** MY ID: ${myid}

<form name="myform" id="myform" action="#" th:action="@{/postEndpoint/{myid}(myid=${myid})}" method="post">

This is not even getting to the controller

Any help would be appreciated! :)

gualizoe
  • 159
  • 1
  • 1
  • 12

2 Answers2

9

This doesn't work like this. Like all server side technologies Thymeleaf templates are executed before being sent to the user, so it can't know what the user will enter and insert it into the action attribute.

You could do something similar with JavaScript, but it would be much easier to use a regular HTML form. That requires you not to use a path variable, but a request parameter in your controller:

@PostMapping("/postEndpoint")
public String pidUserSubmit(@RequestParam(name = "myid") String myid) {
    log.debug("*** MY ID: {}", myid);
    return "redirect:/someOtherPage";
}

<form th:action="@{/postEndpoint}" th:object="${mymodelobject}">
  <input name="myid" type="text" th:value="*{myid}">
</form>

(Don't forget to use th:object with an object that has a property myid, if you want to use the *{...} syntax.)

RoToRa
  • 37,635
  • 12
  • 69
  • 105
  • Thanks for your help! But how do I exactly "link" the html file to the model object? – gualizoe Aug 16 '17 at 20:59
  • I'm not quite sure what you are asking. The object has to be part of the model. There are different ways to do that. – RoToRa Aug 17 '17 at 08:38
2

What you're going to need to do is two things:

The first item is you need to bind th:field to your input, as:

<input id="myid" name="myid" type="text" maxlength="26" title="Please enter a valid ID" class="texter" th:field="*{myid}" th:value="*{myid}">

You'll also want to change how your form posts to save by object. That will look like this:

<form name="myform" id="myform" action="#" th:action="@{/postEndpoint/(object)}" th:object="${object}" method="post">

Replace 'object' with the variable name of the model you're saving. It should all work following this.

jdhurricanes
  • 142
  • 9