简体   繁体   中英

iterate simultaneously over two lists using thymeleaf

<div class="form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-12">Roles
        <span class="required">*</span>
    </label>
    <thbody>
        <td><th:block th:each="myRoles : ${MyRoles}">
            <input type="checkbox" name="roles"
                th:value="${myRoles .id}" checked />
            <label th:text="${myRoles .roleName}"></label>
        </th:block>--</td>
    </thbody>

Current it is showing me only one list(present roles), I want to show all roles which are bind in object ${AllRoles} and checked only those roles which are currently given to a particular user.

I am trying to save roles in set in my controller:

Set<UserRole> myRolesSet;
myRolesSet= myusr.getRoles();

Here's how I am trying to do in view:

<thbody >
        <td><th:block th:each="allRoles : ${allrole}">
        <input  type="checkbox" name="roles" th:value="${allRoles.id}"
        th:checked="${#sets.contains(myRolesSet,allRoles.id)}? 'checked' " />
        <label th:text="${allRoles.roleName}"></label>
        </th:block></td>
</thbody>

You should be doing this like the following code sample:

First you need to put selected roles in a Map in your controller method as follows:

HashMap<Integer, Role> myRolesMap = new HashMap<Integer, Role>();

In this case I assume you are using an Integer key for your hash map.

Secondly you have to iterate over AllRoles list and decide if the user has the currently iterated Role then you should check the checkbox.

    <thbody>
        <td><th:block th:each="role: ${AllRoles}">
            <input type="checkbox" name="roles"
                th:value="${role.id}" th:checked="${#maps.containsKey(myRolesMap, role.id)}" />
            <label th:text="${role.roleName}"></label>
        </th:block>--</td>
    </thbody>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM