Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference data is lost when form fails validation in spring3 annotation based controller

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";
    }

}
like image 463
nont Avatar asked Dec 29 '22 07:12

nont


2 Answers

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".

like image 78
stefanglase Avatar answered Dec 30 '22 19:12

stefanglase


Why not just do

    if (result.hasErrors()) {
        model.put("commandName", "myInfoForm");
        loadReferenceData(model);
        return "contactEdit";
    }
like image 37
Jacob Mattison Avatar answered Dec 30 '22 21:12

Jacob Mattison