Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf dropdown selection

I am using Thymeleaf for one of my java projects. Now, what I am trying to achieve, is when i choose something else from the drop down, and not a default value which is "ALL", and then press submit button [POST], to get the details about the chosen item. I would like to keep that chose item displaying in the drop down, after the submission. And what it does now, it returns back to default value. If I add to the provided code below attribute selected, then it selects all items from the list, which is not acceptable as well, as it end up always displaying the last item of the list.

<div class="controls">
    <select class="form-control" name="example" id="example">
        <option value="0">ALL</option>
        <option th:each="user : ${allUsers}" th:value="${user.id}" th:text="${user.name}">
        </option>
    </select>
</div>

my controller to get the list, I kept it as simple as possible:

@ModelAttribute("allUsers")
public List<User> allUsers() {
    List<User> userList= repo.findAll();
    return userList;
}

also I would like to note, that my object is:

<form class="form-search" action="#" method="post"
      th:action="@{/combinedsearch}"
      th:object="${combinedreport}">

So the idea to use something like this doesn't work

<select th:field="*{user}">, as my object doesn't actually have User as a field.

Any ideas? Help?

like image 801
Alminas Plunge Avatar asked Oct 27 '25 18:10

Alminas Plunge


1 Answers

Basically what I did is in a combinedReport controller, I have extracted that user_ID, which I receive after HTML form submission, then I used it to whatever I need to do in back end, and then I send that user_id back to front end, simply by adding it to a model as an attribute:

model.addAttribute("lastselected", userId);

Then I have created custom logic method in a User's object:

public boolean isSelected(Integer userId){
        if (userId != null) {
            return userId.equals(id);
        }
        return false;
    } 

and then I have modified my code in my thymeleaf template to:

<select class="form-control" name="example" id="example">
     <option value="0">ALL</option>
     <option th:each="user : ${allUsers}"
             th:value="${user.id}"
             th:selected="${user.isSelected(lastselected)}"
             th:text="${user.name}">
     </option>
</select>

and baaaam! it works like a charm !

like image 90
Alminas Plunge Avatar answered Oct 30 '25 09:10

Alminas Plunge