I dont know how to pass an error to thymeleaf outside a form and not specific to a field. Just a small check if the book is on stock. If yes, process everything. If not, throw a error message on the client side.
Controller
@PostMapping("/books/borrow/{id}")
public String borrowBook(@PathVariable int id, Errors errors) {
Book borrowedBook = bookRepository.findById(id);
if (borrowedBook.getAvailableCount() == 0){
errors.rejectValue("onStock", "Book out of stock. Come later...");
return "redirect:/books/";
} else{...}
View
<p th:text="${onStock}"></p>
I don't undestand how to pass the parameter and show it to the client. I did research https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#validation-and-error-messages but they are all specific to a form and field.
What am i doing wrong?
You can use a RedirectAttribute to achieve that:
Controller
@PostMapping("/books/borrow/{id}")
public String borrowBook(@PathVariable int id, Errors errors, RedirectAttributes redirectAttributes) {
Book borrowedBook = bookRepository.findById(id);
if (borrowedBook.getAvailableCount() == 0){
errors.rejectValue("onStock", "Book out of stock. Come later...");
redirectAttributes.addFlashAttribute("errorMessage", "We couldn't process your order!");
return "redirect:/books/borrow/" + id;
} else {
//Process the request
}
Template (HTML)
<div th:if="${errorMessage}">
<div th:text="${errorMessage}"></div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With