Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
832 views
in Technique[技术] by (71.8m points)

option - 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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...