diff --git a/src/main/java/org/springframework/samples/petclinic/owner/PetController.java b/src/main/java/org/springframework/samples/petclinic/owner/PetController.java index fcf431bff..cd85b9c5a 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/PetController.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/PetController.java @@ -125,11 +125,11 @@ class PetController { @PostMapping("/pets/{petId}/edit") public String processUpdateForm(Owner owner, @Valid Pet pet, BindingResult result, - RedirectAttributes redirectAttributes) { + RedirectAttributes redirectAttributes) { String petName = pet.getName(); - // checking if the pet name already exist for the owner + // checking if the pet name already exists for the owner if (StringUtils.hasText(petName)) { Pet existingPet = owner.getPet(petName, false); if (existingPet != null && !existingPet.getId().equals(pet.getId())) { @@ -146,8 +146,21 @@ class PetController { return VIEWS_PETS_CREATE_OR_UPDATE_FORM; } - owner.addPet(pet); - this.owners.save(owner); + + Pet existingPet = owner.getPet(pet.getId()); + if (existingPet != null) { + // Update existing pet's properties + existingPet.setName(pet.getName()); + existingPet.setBirthDate(pet.getBirthDate()); + existingPet.setType(pet.getType()); + + this.owners.save(owner); + } else { + + owner.addPet(pet); + this.owners.save(owner); + } + redirectAttributes.addFlashAttribute("message", "Pet details has been edited"); return "redirect:/owners/{ownerId}"; }