views:

539

answers:

1

I have a simple form that has a select box populated by the database. When validation is triggered the select box is empty. I'm new to spring and I seem to be missing something.

Any help is appreciated? Thanks in advance.

In the controller below sites is the dynamic content.

@RequestMapping("/registration/registration.html")
public ModelMap setupRegistrationForm(HttpServletRequest request, RegistrationForm form) {
    ModelMap map = new ModelMap();
    I18NSite[] sites = new Sites().getSites();
    map.put("sites", sites);
    return map;
}

@RequestMapping(value="/registration/registration.html", method = RequestMethod.POST)
public String saveRegistrationForm(HttpServletRequest request,RegistrationForm form, BindingResult errors) {
    I18NSite site = Sites.getSite(); 
    RegistrationFormValidator validator = new RegistrationFormValidator();
    validator.setDataSource(site.getDataSource());
    validator.validate(form,errors);

    if (errors.hasErrors()) {
        return "registration/registration";
    } else {
        // other code
    }

    return "redirect:/index.html";
}
A: 

Not sure if this helps, but have you tried to expose your reference data, so the data that builds up your selectbox, by using the @ModelAttribute annotation? This should then look similar to this code snippet:

@ModelAttribute("countries")
public List getAllCountries() {
    return geoService.getAllCountries();
}

Or in your case:

@ModelAttribute("sites")
public List getSites() {
    I18NSite[] sites = new Sites().getSites();
    return Arrays.asList(sites);
}

Also a very important issue that took me quite a while to figure out:

Please keep in mind, that your 'backing bean', your pojo that binds to the form fields of your registration form, should exist longer! than just the duration of one request. It, this means always! the same instance, should exist until another Spring mvc controller is called. So the RegistrationForm instance not only exists right after the from is setup and displayed - it should still exist when the POST request is submitted and the RegistrationForm instance is populated with the form data by Spring. You achieve this by the following class level annotation:

// Example for your case... 
@Controller
@SessionAttributes("registrationForm")
public class RegistrationController {
   ...
}

I was googling around for this one for days (REALLY!) - so I really recommend to read this blog entry I found sometime ago. It helped me out of all that Spring MVC documentation hell ;-)

Hope this helps ;-)

tommybrett1977