Setting nested object to null when selected option has empty value
Posted
by Javi
on Stack Overflow
See other posts from Stack Overflow
or by Javi
Published on 2010-04-15T10:08:19Z
Indexed on
2010/04/15
10:33 UTC
Read the original article
Hit count: 342
Hello,
I have a Class which models a User and another which models his country. Something like this:
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 combobox so the user can select his country or can select the undefined option to indicate he doen't 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 the autopopulated object with the user information and I want to have country set to null when the "-Select one-" option has been selected. So I have set a initBinder with a custom editor like this:
@InitBinder
protected void initBinder(WebDataBinder binder) throws ServletException {
binder.registerCustomEditor(Country.class, "country", new CustomCountryEditor());
}
and my editor do something like this:
public class CustomCountryEditor(){
@Override
public String getAsText() {
//I return the Id of the country
}
@Override
public void setAsText(String str) {
//I search in the database for a country with id = new Integer(str)
//and set country to that value
//or I set country to null in case str == null
}
}
When I submit the form it works because when I have country set to null when I have selected "-Select one-" option or the instance of the country selected. The problem is that when I load the form I have a method like the following one to load the user information.
@ModelAttribute("user")
public User getUser(){
//loads user from database
}
The object I get from getUser() has country set to a specific country (not a null value), but in the combobox is not selected any option. I've debugged the application and the CustomCountryEditor works good when setting and getting the text, thoughgetAsText method is called for every item in the list "countries" not only for the "country" field.
Any idea? Is there a better way to set null the country object when I select no country option in the combobox?
Thanks
© Stack Overflow or respective owner