0

Can't seem to get addFlashAttribute message to display. It works on another controller but not on this one. My error check (if (!ingredientRepository...)) appears to work and the object is NOT saved due to error; however, the message is either not passed or just doesn't display.

< p th:if="${ingredientError}" th:text="${ingredientError}" class="alert alert-danger" /></ p>

Controller Mappings:

@GetMapping("")
public String index(Model model, HttpServletRequest request) {
    model.addAttribute("ingredients", ingredientRepository.findAll(Sort.by(Sort.Direction.ASC, "name")));
    model.addAttribute(new Ingredient());
    return "ingredients/index";
}

@PostMapping("add")
public String addIngredient(@ModelAttribute @Valid Ingredient newIngredient, Errors errors, Model model, RedirectAttributes ra) {
    if (errors.hasErrors()) {
        model.addAttribute("ingredients", ingredientRepository.findAll(Sort.by(Sort.Direction.ASC, "name")));
        model.addAttribute("errors", errors);
        return "ingredients/index";
    }

    if (!ingredientRepository.findByName(newIngredient.getName()).isEmpty()) {
        ra.addFlashAttribute("ingredientError", "Ingredient already exists.");
        return "redirect:";
    }

    ingredientRepository.save(newIngredient);
    return "redirect:";
}
  • Is that `return "redirect:"` exactly as you have it in your code? There should normally be a url there. Something like `return "redirect:/"`. – Wim Deblauwe Sep 07 '22 at 06:57
  • Got it to work. It has a request mapping on the controller @RequestMapping("ingredients") so it was redirecting to the index page of ingredients folder correctly but not passing the redirect message for some reason. I change it to return "redirect:/ingredients"; and it finally worked. Thanks! – James Darren Sep 07 '22 at 21:35

2 Answers2

0

Your th:if is faulty I believe. It should be <p th:if="${ingredientError != null}" th:text="${ingredientError}" class="alert alert-danger" /></ p>.

th:if="${ingredientError}" only works for pressent boolean variables.

Ralan
  • 651
  • 6
  • 17
  • That had no effect. I assume it verifies that the record exists, redirect the page, but the flash msg just won't show. I use virtually the same code in a different section and it works, displays the error message. Driving me crazy. LOL – James Darren Sep 06 '22 at 22:47
0

When requesting a redirect via the return "redirect:", you should include the url to redirect to. For example: return "redirect:/ingredients"

Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211