Reputation: 20571
I have form-backing object:
public class MyDto {
private Set<MyEnum> myEnum = new HashSet<MyEnum>();
// getters/setters
public MyEnym[] getMyEnumValues() {
return MyEnum.values();
}
}
public MyEnum {
A, B, C
}
What is the way to show all enum values in <form:select multiple="true"/>
and achieve automatically mapping of selected values to myEnum
field in my form-backing object?
Update: Some code:
<form:select path="myEnum" multiple="true" items="${myDto.myEnumValues}"/>
When submitting form, selected values in multiselect are presented in HTTP request:
myEnum: A
myEnum: B
public String saveMyDto(@Valid @ModelAttribute("myDto") MyDto myDto) {
log.debug("Enum list: " + myDto.myEnum().toString());
....
}
Upvotes: 1
Views: 1880
Reputation: 120771
The key idea is to assign the values to the item
attribute of form:select
.
I the controller that populate the view with the form add
modelMap.addAttribute("possibleValues", MyEnum.values);
in the jsp use:
<form:select multiple="true" items="${possibleValues}" path="myDto.myEnum"/>
(On the other hand, I remember that I have had a look at the select tag implementation of spring, and found that it the value of the actual value is an Enum, then spring automatically use all Enum.values
as default value for items
(but I am not 100% sure) )
The Controller method should look like
@RequestMapping(value="/form", Method=RequestMethod.GET)
public ModelAndView whatever() {
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("possibleValues", MyEnum.values);
return new ModelMap("nameOfTheView", modelMap);
}
@RequestMapping(value="/whatever", Method=RequestMethod.POST)
public ModelAndView whatever(MyDto myDto) {
Sysout.println(myDto);
}
Upvotes: 2