I do like to have bind checkboxes into 1 String object, I noticed multiples checkboxes is checked, then at server-side will received String of "value1,value2,value4" which is selected checkboxes value. But the String of "value1,value2,value4" cannot generate page that check the checkboxes. Any workaround of suggested solution?
What I done a work around, but still have bug that cause other fields failed to bind due to multiple bind to same path (eg: path="types"):
@RequestMapping(value = "/someUrl", method = RequestMethod.GET)
public String displayInputCustomClass(Map<String, Object> map) {
CustomClass customClass = new CustomClass();
//customerClass.types => is a String
map.put("customClass", customClass);
map.put("types", getTypes());
return "/internalView/inputForm";
}
@RequestMapping(value = "/someUrl/{ccId}", method = RequestMethod.POST)
public String saveCustomClass(Map<String, Object> map, @PathVariable Integer ccId) {
if (errors.getErrorCount() > 0) {
map.put(BindingResult.MODEL_KEY_PREFIX + "customClass", errors);
map.put("types", getTypes());
return "/internalView/inputForm";
}else{
//Save the object into DB
}
}
private Map getTypes(){
Map<String, String> types = new LinkedHashMap();
types.put("value1", "1st type");
types.put("value2", "2nd type");
types.put("value3", "3rd type");
types.put("value4", "4th type");
return types;
}
In the JSP, I do:
<c:set var="previousTypes" value="${fn:split(customClass.types, ',')}" scope="request"/>
<c:set var="type1Var" value="" scope="request"/>
<c:set var="type2Var" value="" scope="request"/>
<c:set var="type3Var" value="" scope="request"/>
<c:set var="type4Var" value="" scope="request"/>
<c:forEach items="${requestScope.types}" var="type" >
<c:forEach items="${previousTypes}" var="previousType">
<c:if test="${type.value == previousType }">
<c:if test="${type.value == 'value1'}">
<c:set var="value1Var" value="true" scope="request"/>
</c:if>
<c:if test="${type.value == 'value2'}">
<c:set var="value2Var" value="true" scope="request"/>
</c:if>
<c:if test="${type.value == 'value3'}">
<c:set var="value3Var" value="true" scope="request"/>
</c:if>
<c:if test="${type.value == 'value4'}">
<c:set var="value4Var" value="true" scope="request"/>
</c:if>
</c:if>
</c:forEach>
</c:forEach>
Please check for custom class type(s):
<c:if test="${empty value1Var}">
<form:checkbox path="types" value="value1" /> Value1
</c:if>
<c:if test="${!empty value1Var}">
<form:checkbox path="types" value="value1" checked="checked" /> Value1
</c:if>
<c:if test="${empty value2Var}">
<form:checkbox path="types" value="value2" /> Value2
</c:if>
<c:if test="${!empty value2Var}">
<form:checkbox path="types" value="value2" checked="checked" /> Value1
</c:if>
// ... Same for generate value3 & value4 checkboxes
I'm new to spring mvc, this is what I can think of, any other binding workaround to solve 1 String map to multiple checkboxes solution?
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire