Reputation: 1681
There is a search form in html:
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?
After receiving search results, 'options' should have remained "Mobile Phone":
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...
Upvotes: 1
Views: 2300
Reputation: 985
If you are using spring MVC with Thymeleaf, you can following steps.
Step-1 controller
@PostMapping("/searchorder")
public ModelAndView searchOrders(@Valid SearchOrderFilter searchOrderFilter, BindingResult bindingResult)
{
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("searchOrderFilter", searchOrderFilter);
return modelAndView;
}
Step-1 thymeleaf
<select th:object = "${fareMediaTypeList}" id="fareMediaType" name="fareMediaType">
<option th:each="fareMediaType : ${fareMediaTypeList}"
th:value="${fareMediaType.id}" th:text="${fareMediaType.Desc}"
th:selected="${fareMediaType.id.equals(searchOrderFilter.fareMediaTypeId)}">
</option>
Upvotes: 0
Reputation: 1681
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
}
Upvotes: 1
Reputation: 3777
I'm assuming the page reloads upon hitting "Search". To keep the selection, you'd have to expand your DTO with the information "is this selection selected previously?". Your Thymeleaf sample will result in the following:
<label class="labelWidthExtra">
<select name="typeOfSearch">
<option th:each="s : ${selection}"
th:text="${s.text}"
th:selected="${s.selected}">
</option>
</select>
</label>
Upvotes: 1