I have a Model that holds a list of Countries (List) and a user object that holds a Country object. I have a view that the user can select his country.
This is snippet of
You need to somehow tell Spring to convert a String
to a Country
. Here is an example :
@Component
public class CountryEditor extends PropertyEditorSupport {
private @Autowired CountryService countryService;
// Converts a String to a Country (when submitting form)
@Override
public void setAsText(String text) {
Country c = this.countryService.findById(Long.valueOf(text));
this.setValue(c);
}
}
and
...
public class MyController {
private @Autowired CountryEditor countryEditor;
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Country.class, this.countryEditor);
}
...
}