Skip to content

Commit

Permalink
Fix pet update functionality - Fixed issue where editing a pet's type…
Browse files Browse the repository at this point in the history
… or name wasn't persisting - Updated processUpdateForm to modify existing pet instead of adding new one - Added proper handling of existing pet update Fixes #1752
  • Loading branch information
VishantOwO committed Dec 31, 2024
1 parent 6148ddd commit 101ee08
Showing 1 changed file with 17 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,11 @@ public String initUpdateForm() {

@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())) {
Expand All @@ -146,8 +146,21 @@ public String processUpdateForm(Owner owner, @Valid Pet pet, BindingResult resul
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}";
}
Expand Down

0 comments on commit 101ee08

Please sign in to comment.