Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thymeleaf multiple selected on edit

I am totally changing this question, as part of it was answered here with great help of Avnish! Tom sent me to the right direction so thank you Tom!

My problem is that I do not know how to tell Thymeleaf to preselect object elements when editing it.

Let me show you:

looks like this

This solution works:

<select class="form-control" id="parts" name="parts" multiple="multiple">
    <option th:each="part : ${partsAtribute}"
            th:selected="${servisAttribute.parts.contains(part)}"
            th:value="${part.id}"
            th:text="${part.name}">Part name</option>
</select>

I have tried this:

<select class="form-control" th:field="*{parts}" multiple="multiple">
    <option th:each="part : ${partsAtribute}"
            th:field="*{parts}"
            th:value="${part.id}"
            th:text="${part.name}">Part name</option>
</select>

did not work. I also tried this:

<select class="form-control" th:field="*{{parts}}" multiple="multiple">
    <option th:each="part : ${partsAtribute}"
            th:field="*{parts}"
            th:value="${part.id}"
            th:text="${part.name}">Part name</option>
</select>

did not work either. I have tried removing th:field="*{parts}" from the option tag, same result..

If I change th:value to ${part} it works, but then it does not send back string of ids like [2,4,5,6,...], but Part instances like [Part@43b45j, Part@we43y7,...]...

UPDATE: I just noticed that this works if only one part is selected:

<select class="form-control" th:field="*{parts}" multiple="multiple">
    <option th:each="part : ${partsAtribute}"
            th:field="*{parts}"
            th:value="${part.id}"
            th:text="${part.name}">Part name</option>
</select>

If multiple parts are selected, it does not work...

like image 787
Blejzer Avatar asked Mar 07 '14 09:03

Blejzer


1 Answers

After discussion on the Thymeleaf forum, I implemented a full working example at https://github.com/jmiguelsamper/thymeleafexamples-selectmultiple

I think that the only problem with your final code is that you have to use double bracket syntax to invoke the conversionService:

th:value="${{part}}"

It is also important to implement proper equals() and hashcode() methods in your Part class to assure proper comparison.

I hope my example helps other users with similar problems in the future.

like image 176
user211430 Avatar answered Sep 23 '22 17:09

user211430