I have a class that models a user and another that models his country. Something like that:
public class User{ private Country country; //other attributes and getter/setters } public class Country{ private Integer id; private String name; //other attributes and getter/setters }
I have a Spring form where I have a combo box, so the user can select their country or select the undefined option to indicate that they do not want to provide this information. So I have something like this:
<form:select path="country"> <form:option value="">-Select one-</form:option> <form:options items="${countries}" itemLabel="name" itemValue="id"/> </form:select>
In my controller, I get an autopopulated object with user information, and I want the country to set to null when the option "-Select one" was selected. So I installed initBinder with a custom editor as follows:
@InitBinder protected void initBinder(WebDataBinder binder) throws ServletException { binder.registerCustomEditor(Country.class, "country", new CustomCountryEditor()); }
and my editor will do something like this:
public class CustomCountryEditor(){ @Override public String getAsText() {
When I submit a form, it works, because when I have a country that is null, when I selected "-Select one option" or an instance of the selected country. The problem is that when I load the form, I have a method like the following for loading user information.
@ModelAttribute("user") public User getUser(){
The object I get from getUser () has a country set to a specific country (not a null value), but no option has been selected in combobox. I debugged the application, and CustomCountryEditor works fine when setting up and receiving text, the whatgetAsText method is called for each element in the "country" list, not only for the "country" field.
Any idea? Is there a better way to set the country object to null when I did not select the country parameter from the drop down list?
thanks