Search code examples
formsvalidationspring-mvcthymeleaf

"${#fields.hasErrors('*')}" always false - Redirect Problem


My controller looks like this:

    @PostMapping("/event/{id}")
    public String save(@PathVariable("id") long id, @Valid Form form, BindingResult bindingResult ) {

        if (!bindingResult.hasErrors()) {
          //No errors
          //No return
        }

        return "redirect:/event/{id}";               
    }

My @GetMapping is:

 @GetMapping("/event/{id}")
    public ModelAndView eventDetail(@PathVariable("id") long id) {

        ModelAndView model = new ModelAndView("event/details");
        Event event = eventoRepository.findById(id).get();
        model.addObject("event", evento);
        model.addObject("guests", event.getGuests());
        model.addObject("guest",new Guest());

        return model;

    }

I know that "${#fields.hasErrors('*')}" is always false because redirect. (right?)

How return to this path /event/{id} without redirect?


Solution

  • I know that "${#fields.hasErrors('*')}" is always false because redirect. (right?)

    Right. It looks like you always redirect. Because of that a method annotated with @GetMapping("/event/{id}") is called, the form most likely is reseted to fresh state and there are no more errors making expression always false.

    How return to this path /event/{id} without redirect?

    Simply return name of the view (template) containing the form. Most likely it's the same what's returned by method annotated with @GetMapping("/event/{id}").

    You should follow an approach from this guide. Return without redirect if the form contains error, and redirect otherwise.

    Edit: You should also provide additional objects to the model. Instead of populating model in each method (Get, Post etc.) you may extract common objects to a method annotated with @ModelAttribute. According to javadoc such a method can accept similar parameters as methods annotated with @RequestMapping.

    For your case something like this should work fine:

        @ModelAttribute
        void supplyModel(@PathVariable("id") long id, Model model) {
            Event event = eventoRepository.findById(id).get();
            model.addAttribute("event", evento);
            model.addAttribute("guests", event.getGuests());
            model.addAttribute("guest",new Guest());
        }
    
        @GetMapping("/event/{id}")
        public String eventDetail(@PathVariable("id") long id) {
            return "event/details";
    
        }
    
        @PostMapping("/event/{id}")
        public String save(@PathVariable("id") long id, @Valid Form form, BindingResult bindingResult ) {
    
            if (bindingResult.hasErrors()) {
                // Has errors
                return "event/details";
            }
    
            // No errors
            return "redirect:/event/" + id;
        }