Search code examples
javahtmlthymeleaf

Thymeleaf select option resets to default


There is a search form in html: Initial form

The default value in options is "First Name". When I choose, lets say, search by mobile phone, press "Search" and get the resulting page, the form options get reset to default value. But I need it to keep the variant I selected, in this case it was "Mobile Phone". What has to be changed in html?

Form filled in: Form filled in

After receiving search results, 'options' should have remained "Mobile Phone": After receiving search results

html code:

<label class="labelWidthExtra">
    <select name="typeOfSearch">
        <option th:each="s : ${selection}" th:text="${s}">
        </option>
    </select>
</label>

In case of JSP + Spring tags the same is resolved very easily:

<label>
    <sf:select path="typeOfSearch" items="${selection}"/>
</label>

But Thymeleaf is confusing...


Solution

  • The solution was eventually found.

    html side:

    <option th:each="s : ${selection}"
            th:text="${s}"
            th:selected="${s.equals(selector)}">
    </option>
    

    Controller side (in Kotlin):

    @PostMapping(value = "/contactsSearch")
        fun searchForContacts(@RequestParam(value = "typeOfSearch") typeOfSearch: String,
                              @RequestParam(value = "searchParam") searchParam: String, model: Model): String {
            val contacts = contactService.retrieveContactsBySearch(typeOfSearch, searchParam)
            model.addAttribute(CONTACT_LIST, contacts)
            model.addAttribute(SELECTOR, typeOfSearch)
            model.addAttribute(SEARCH_PARAM, searchParam)
            model.addAttribute(SELECTION, SELECTION_PARAMS)
    
            return CONTACTS_SEARCH
        }