参考:Thymeleaf获取复选框参数和回显 https://blog.csdn.net/Qii_yuan/article/details/88651078
方式一、
HTML:
遍历所有渠道,判断每个渠道是否存在已有渠道集合channelList中,存在,则设置当前渠道checked属性为true,否则为false
<!-- 若依重新封装了复选框样式,所以这里在label上循环所有渠道 这里dict_channel为渠道字典-->
<label class="col-sm-3 control-label">渠道:</label>
<div class="col-sm-9">
<label th:each="dict:${@dict.getType('dict_channel')}" class="check-box">
<!-- 这里的 channelList 为后端传过来的字符串集合List<String> -->
<input type ="checkbox" id="channel" name="channel"
th:value="${dict.dictValue}"
th:text ="${dict.dictLabel}"
th:attr ='checked=${channelList.contains(dict.dictValue)?true:false}'>
</label>
</div>
/**
* 修改
*/
@GetMapping("/edit/{testId}")
public String edit(@PathVariable("testId") Long testId, ModelMap modelMap)
{
String channels = "1001,1002,1003";//已选中的渠道
//将字符串转换为List集合
List<String> channelList = Arrays.asList(channels.split(","));
modelMap.put("channelList", channelList);
return prefix + "/edit";
}
方式二、
遍历对象集合brands,使用th:field方式判断并回显选中
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
<form class="form-horizontal m" id="form-BranchPlace-edit" th:object="${branchPlace}">
<input id="branchPlaceId" name="branchPlaceId" th:field="*{branchPlaceId}" type="hidden">
<!-- 注意上面form的 th:object 为对象,下面通过*{}方式获取对象branchPlace的属性-->
<div class="form-group">
<label class="col-sm-3 control-label">快递品牌:</label>
<div class="col-sm-9">
<label th:each="brand:${brands}" class="check-box">
<input id="brands" name="brands" th:field="*{selectBrands}" type="checkbox" th:value="${brand.brandId}" th:text="${brand.brandName}">
</label>
</div>
</div>
</form>
</div>
</body>
/**
* 修改快递网点
*/
@GetMapping("/edit/{branchPlaceId}")
public String edit(@PathVariable("branchPlaceId") Long branchPlaceId, ModelMap mmap) {
BranchPlace branchPlace = randService.selectBranchPlaceById(branchPlaceId);
String brandIds = "1001,1002,1003";
String[] selectBrands = brandIds.split(",");
branchPlace.setSelectBrands(selectBrands);
mmap.put("branchPlace", branchPlace);
List<Brand> brands = randService.selectAllBrand();
mmap.put("brands",brands);
return prefix + "/edit";
}
public class Brand extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 主键ID */
private Long brandId;
/** 品牌简称 */
private String brandName;
//getter setter.. 等代码
}