The below code works fine when I try to save a single value of miniApple. I can see the value of miniApple object value in argument of controller i.e., apple. However I am not able to binder if there are multiple values. Not sure what should be the syntax to write inside the initBinder method for converting the string (comma separated value) into List of custom objects(here List of MiniApple)
When I select multiple values, I can the text value in setAsText() as comma separated values( eg: "miniApple1, miniApple2,miniAPlle3")
Controller method save()
public ModelAndView save(@ModelAttribute("Apple") Apple apple, BindingResult result, SessionStatus status) {
}
Init Binder method
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(MiniApple.class, new MiniAppleEditor(this.miniAppleService, true));
}
Custom Editor class with setAsText method
public class MiniAppleEditor extends PropertyEditorSupport {
/** The mini apple service. */
private final MiniAppleService miniAppleService;
/** Whether or not to allow null values. */
private boolean allowEmpty;
/**
* @param miniAppleService the miniAppleService to set
*/
public MiniAppleEditor(MiniAppleService miniAppleService) {
this(miniAppleService, false);
}
/**
* @param miniAppleService the miniAppleService to set
* @param allowEmpty indicates to allow empty mini apple.
*/
public MiniAppleEditor(MiniAppleService miniAppleService, boolean allowEmpty) {
this.miniAppleService = miniAppleService;
this.allowEmpty = allowEmpty;
}
/**
* @param text the id representing the MiniApple object.
*/
@Override
public void setAsText(String text) {
if (allowEmpty && !StringUtils.hasLength(text)) {
setValue(null);
} else {
setValue(miniAppleService.getMiniApple(Integer.parseInt(text)));
}
}
/**
* @return the Id as a String
*/
@Override
public String getAsText() {
MiniApple miniApple = (MiniApple) getValue();
if (miniApple == null) {
return "";
} else {
return miniApple.getAppleName();
}
}
}
Object which will get the values binded as an argument of controller save () method
@Entity
@Table("tbl_apple")
public class Apple implements Serializable {
private MiniApple miniApple;
getter/setter;
}