<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.
我正在尝试将角色保存在我的 Controller 中:
Set<UserRole> myRolesSet;
myRolesSet= myusr.getRoles();
这是我在 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>
最佳答案
您应该像下面的代码示例一样执行此操作:
首先,您需要将选定的角色放入 Controller 方法的 map 中,如下所示:
HashMap<Integer, Role> myRolesMap = new HashMap<Integer, Role>();
在本例中,我假设您使用整数键作为 HashMap 。
其次,您必须迭代 AllRoles 列表并确定用户是否具有当前迭代的角色,然后您应该选中该复选框。
<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>
关于java - 使用 thymeleaf 同时迭代两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54435381/