0

When searching, if we select a given field to search within and submit, our choice is forgotten. How could someone modify the view template to keep the previous search field selected when displaying results?

I have read many other SO questions and the thymeleaf documentation here but have not found a suitable answer yet.

One can hard code a string (like employer) with the following:

search.html snippet

<span th:each="column : ${columns}">
  <input
    type="radio"
    name="searchType"
    th:id="${column.key}"
    th:value="${column.key}"
    th:checked="${column.key == 'employer'}"/>

    <label th:for="${column.key}" th:text="${column.value}"></label>
 </span>

SearchController.html snippet

@RequestMapping(value = "")
public String search(Model model) {
    model.addAttribute("columns", columnChoices);
    return "search";
}

How can I persist the user selected radio value upon POST in Thymeleaf Spring? (and default to the first, value on the GET)

1 Answer 1

0

http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#creating-a-form

Command object.

public class Search {
    // default "employer"
    private String type = "employer";

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

Controller

@GetMapping
public String search(Model model) {
    model.addAttribute("columns", columnChoices);
    model.addAttribute("search", new Search());
    return "search";
}

@PostMapping
public String search(@ModelAttribute Search search) {
    // Search's attributes match form selections.
}

With search as your command object, a radio buttons should look like this:

<form th:object="${search}">
    <th:block th:each="column: ${columns}">
        <input type="radio" th:value="${column.key}" th:id="${column.key}" th:field="*{type}" />
        <label th:for="${column.key}" th:text="${column.value}" />
    </th:block>
</form>
3
  • Thank you for your assistance, however I am not trying to keep employer as the only field, I am attempting to keep whatever the user selects from say 5 radio options, to persist, after a user POSTs, and default to the first option if they are just using a GET. Commented Aug 19, 2017 at 21:17
  • I am pulling from a .csv for the columns. Commented Aug 19, 2017 at 21:19
  • That doesn't really change the answer. You can have several radio buttons with different values (and the same th:field). Whichever radio is selected is the one that is POSTed. If column isn't the correct option for your command object, then you should create one.
    – Metroids
    Commented Aug 21, 2017 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.