views:

43

answers:

2

I'm doing the spring 3 annotation based controller thing. Problem is, when it fails validation, the reference data is lost, namely the countryDivisions stuff. I didn't put it in the form because its not user editable data, and the orthodoxy here is that only user-editable data goes in the form. Do I have any other choice?

@Controller
public class MyInfoController {

   @Autowired
    private MyInfoFormValidator validator;

 private void loadReferenceData(ModelMap model) {
        model.put("countryDivisions",countryDivisionService.getCountryDivisionOrderedByCode());
    }

  @ModelAttribute
    private MyInfoForm loadMyInfo() {
        MyInfoForm form = new MyInfoForm();
     //load it up
    return form;
    }


    @RequestMapping(value="/editMyInfo", method = RequestMethod.GET)
    public String editMyInfo(ModelMap model ) {
        loadReferenceData(model);
        return "contactEdit";
    }

  @RequestMapping(value="/editMyInfo", method = RequestMethod.POST)
    public String saveMyInfo(ModelMap model, MyInfoForm form,BindingResult result ) {
        validator.validate (form,result);
        if (result.hasErrors()) {
            model.put("commandName", "myInfoForm");
            return "contactEdit";
        }
         //save some stuff
        return "redirect:viewMyInfo";
    }

}
+1  A: 

Why not just do

    if (result.hasErrors()) {
        model.put("commandName", "myInfoForm");
        loadReferenceData(model);
        return "contactEdit";
    }
JacobM
+3  A: 

You should provide reference data like your CountryDivisions with the help of the annotation @ModelAttribute. This has the great advantage that you don't need to repeat yourself over and over and provide the same data within multiple methods.

For your example I would provide something like this:

@ModelAttribute("countryDivisions")
public List<CountryDivision> populateCountryDivisions() {
    return countryDivisionService.getCountryDivisionOrderedByCode();
}

This gives your views access to a model attribute called "countryDivisions" that holds a list of "CountryDivison"-objects provided by the service method from your "countryDivisionService".

codescape
Thanks! That makes sense. For some reason, it didn't occur to me to have more than one method annotated at @ModelAttribute
nont
You are welcome! It is completely valid to have multiple methods annotated with @ModelAttribute in one single controller.
codescape