I am working on CRUD application which helps to keep count of inventory.
I have a controller editDevice()
that edit inventory card of device. Here I add an attribute “acts” which contains all previously created acts with this device. History of device acts displays on the html form. Method showActsByDevice()
takes data from postgresql view. Respectively I made a controller updateDevice()
where I handle DuplicateKeyException
and return html form.
@GetMapping("/{inventoryCard}/edit")
public String editDevice(@PathVariable("inventoryCard") String inventoryCard, Model model){
model.addAttribute("device", deviceDAO.showOne(inventoryCard));
model.addAttribute("acts", actDAO.showActsByDevice(inventoryCard));
return "property/edit_device.html";
}
@PatchMapping("/{inventoryCard}")
public String updateDevice(@ModelAttribute("device") @Valid Device device,
BindingResult bindingResult,
@PathVariable("inventoryCard") String inventoryCard){
try{
deviceDAO.update(inventoryCard, device);
} catch(DuplicateKeyException e){
bindingResult.rejectValue("inventoryCard", "error.inventoryCard", "This inventory card already used");
}
if(bindingResult.hasErrors()){
return "property/edit_device.html";
}
return "redirect:/device/show_all";
}
But then I don’t have “acts” attribute in model and then I cannot show acts of device.
I have tried to use redirectAttributes
but it’s not displaying error message and as I understand it, in this case I should not use it.
if(bindingResult.hasErrors()){
redirectAttributes.addFlashAttribute("errors", bindingResult.getFieldErrors());
redirectAttributes.addFlashAttribute("device", deviceDAO.showOne(inventoryCard));
redirectAttributes.addFlashAttribute("acts", actDAO.showActsByDevice(inventoryCard));
return "redirect:/device/{inventoryCard}/edit";
}
In addition, I cannot use the method with @ModelAttribute
annotation because I need the value of device inventory card.
How I should handle this exception and keep acts on html form? Thanks in advance.
sirensonthewayy– is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.