Kunal
Kunal

Reputation: 327

Spring MVC Validate form and return data if has errors

I can successfully validate my form and even return the errors. My problems started when my view had a few selects that needed to be populated with the data coming from the controller.

When i do model.addAttribute(...) it stops passing the errors to the view:

 public String registerSubmit(@Valid @ModelAttribute("jconcorrente") Jconcorrentes concorrente, BindingResult result, HttpServletRequest request, Model model){

         if(result.hasErrors()) {
             model.addAttribute("listJdistrito", this.jdistritoService.listJdistrito());
             model.addAttribute("listJtipocodiden", this.jtipodocidenService.listJtipodociden());
             model.addAttribute("jconcorrente", new Jconcorrentes());
                return "register";
            }

So my question is how can i pass the data without affecting the validation errors?

Upvotes: 0

Views: 815

Answers (1)

Paulius Matulionis
Paulius Matulionis

Reputation: 23413

My guess is that your errors aren't getting populated because you are adding new instance of your model attribute directly into the model.

Try to remove this line:

model.addAttribute("jconcorrente", new Jconcorrentes());

from your if statement and create new method like this:

@ModelAttribute("jconcorrente")
public Jconcorrentes getJconcorrentes() {
    return new Jconcorrentes();
}

Leave everything else the same and it should work.

Upvotes: 1

Related Questions