Skip to content

Commit 2aa53f9

Browse files
VishantOwODave Syer
authored andcommitted
Fix pet update functionality
- Fixed issue where editing a pet's type 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
1 parent 6328d2c commit 2aa53f9

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

src/main/java/org/springframework/samples/petclinic/owner/PetController.java

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ public String processUpdateForm(Owner owner, @Valid Pet pet, BindingResult resul
129129

130130
String petName = pet.getName();
131131

132-
// checking if the pet name already exist for the owner
132+
// checking if the pet name already exists for the owner
133133
if (StringUtils.hasText(petName)) {
134134
Pet existingPet = owner.getPet(petName, false);
135135
if (existingPet != null && !existingPet.getId().equals(pet.getId())) {
@@ -146,10 +146,28 @@ public String processUpdateForm(Owner owner, @Valid Pet pet, BindingResult resul
146146
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
147147
}
148148

149-
owner.addPet(pet);
150-
this.owners.save(owner);
149+
updatePetDetails(owner, pet);
151150
redirectAttributes.addFlashAttribute("message", "Pet details has been edited");
152151
return "redirect:/owners/{ownerId}";
153152
}
154153

154+
/**
155+
* Updates the pet details if it exists or adds a new pet to the owner.
156+
* @param owner The owner of the pet
157+
* @param pet The pet with updated details
158+
*/
159+
private void updatePetDetails(Owner owner, Pet pet) {
160+
Pet existingPet = owner.getPet(pet.getId());
161+
if (existingPet != null) {
162+
// Update existing pet's properties
163+
existingPet.setName(pet.getName());
164+
existingPet.setBirthDate(pet.getBirthDate());
165+
existingPet.setType(pet.getType());
166+
}
167+
else {
168+
owner.addPet(pet);
169+
}
170+
this.owners.save(owner);
171+
}
172+
155173
}

0 commit comments

Comments
 (0)