Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created September 4, 2019 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/51768839ee36eceeade0f6872f256b00 to your computer and use it in GitHub Desktop.
Save parzibyte/51768839ee36eceeade0f6872f256b00 to your computer and use it in GitHub Desktop.
// Se colocó el parámetro ID para eso de los errores, ya sé el id se puede recuperar
// a través del modelo, pero lo que yo quiero es que se vea la misma URL para regresar la vista con
// los errores en lugar de hacer un redirect, ya que si hago un redirect, no se muestran los errores del formulario
// y por eso regreso mejor la vista ;)
@PostMapping(value = "/editar/{id}")
public String actualizarProducto(@ModelAttribute @Valid Producto producto, BindingResult bindingResult, RedirectAttributes redirectAttrs) {
if (bindingResult.hasErrors()) {
if (producto.getId() != null) {
return "productos/editar_producto";
}
return "redirect:/productos/mostrar";
}
Producto posibleProductoExistente = productosRepository.findFirstByCodigo(producto.getCodigo());
if (posibleProductoExistente != null && !posibleProductoExistente.getId().equals(producto.getId())) {
redirectAttrs
.addFlashAttribute("mensaje", "Ya existe un producto con ese código")
.addFlashAttribute("clase", "warning");
return "redirect:/productos/agregar";
}
productosRepository.save(producto);
redirectAttrs
.addFlashAttribute("mensaje", "Editado correctamente")
.addFlashAttribute("clase", "success");
return "redirect:/productos/mostrar";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment