Search code examples
javaspringspring-mvcspring-bootthymeleaf

Spring "Neither BindingResult nor plain target object for bean name" error when submitting form on view with multiple forms


Currently I am experiencing rather nasty problem and can't find a way to get rid of it. I am using Thymeleaf and Spring Boot in my project. I was looking at various topics here and on other forums, with no luck in solving the above. I have a view with two, not nested forms, with separate submit buttons and separate actions:

<form id="bidForm" th:action="@{'/auction/bid/' + ${auctionDto.id}}" 
th:object="${bidDto}" method="post">
/* more html code here */
</form>

<form id="buyoutForm" th:action="@{'/buyout/confirm-buyout'}" 
th:object="${buyoutDto}" method="post">
/* more html code here */
</form>

The view is generated by following method from the controller:

@GetMapping("/get/{id}")
public ModelAndView getAuction(@PathVariable String id) {
    ModelAndView modelAndView = new 
    ModelAndView(Templates.AuctionTemplates.ITEM);
    modelAndView.addObject("auctionDto", getAuctionService.getOne(id));
    modelAndView.addObject("bidDto", new BidDto());
    modelAndView.addObject("buyoutDto", new BuyoutDto());
    return modelAndView;
}

The method mappings specified in th:action are in two different controllers. Controller with action for "bidForm":

@Controller
@RequestMapping("/auction")
public class AuctionController {

   @PostMapping("/bid/{id}")
   public ModelAndView bid(@PathVariable String id, 
    @ModelAttribute("bidDto") 
    @Valid BidDto bidDto, BindingResult bindingResult, Principal principal) {
    /* more code here */
    }
}

and for "buyoutForm":

@Controller
@RequestMapping("/buyout")
public class BuyoutController {

    @PostMapping("/confirm-buyout")
    public ModelAndView confirmBuyout(@Valid @ModelAttribute("buyoutDto") 
    BuyoutDto buyoutDto) {
        ModelAndView modelAndView = new ModelAndView();
        return modelAndView;
        }
   }

Now, to the problem: when I submit the "bidForm" using corresponding button, I get an error:

Neither BindingResult nor plain target object for bean name "buyoutDto"

I have no idea why Spring expects an object of "BuyoutDto" class in the "bid" method. It's the first time I am experiencing this problem. Could you help me solve it, please? Regards, Lukas.


Solution

  • I think that the error occurs because in your bid method you do not return the object buyoutDto. When you return from this method, do you go again in the same page (the page that has the two forms)?

    For example your code should look like

    @PostMapping("/bid/{id}")
       public ModelAndView bid(@PathVariable String id, 
        @ModelAttribute("bidDto") 
        @Valid BidDto bidDto, BindingResult bindingResult, Principal principal) {
             /* more code here */
             modelAndView.addObject("buyoutDto", new BuyoutDto());
        }