'Attempting to add a "delete" button to existing "details" view
I am working on a group project that allows users to create, store, edit, and delete notes.
We are able to access the stored notes via a very basic "details" view, and would like to make the "delete" functionality available within that details view without having to create a separate "delete" view.
As of right now, this is how our "details" handler looks in our controller:
public String displayNoteDetails(Model model, @RequestParam int id, @RequestParam int userId) {
Optional<SecretNote> result = noteRepository.findById(id);
if (result.isEmpty()) {
model.addAttribute("title", "Invalid Note ID: " + id);
return "redirect:../";
} else {
SecretNote secretNote = result.get();
model.addAttribute("title", secretNote.getName() + " Details");
model.addAttribute("secretNote", secretNote);
}
return "notes/details";
}
}
I was able to get a "delete" button to show up in the "details" view with the following:
<form th:action="delete" method="post" th:object="${secretNote}">
<input type="hidden" th:field="${secretNote.id}"/>
<button type="submit" value="Submit" class="btn btn-danger">Delete</button>
</form>
However, when clicking on said "delete" button, it is redirecting to http://localhost:8080/notes/delete
, presumably because of how I have the "delete" button set up. I'd like to add code to the displayNoteDetails
that would allow me to use noteRepository.deleteById(id);
and then redirect to "notes/index"
(the user home page that displays all notes).
FWIW, here's how we had the delete handlers when we were planning on doing a separate view:
@GetMapping("delete")
public String displayDeleteNoteForm(@RequestParam int id, @RequestParam int userId) {
noteRepository.deleteById(id);
return "notes/index";
}
@PostMapping("delete")
public String processDeleteNoteForm(Model model, @RequestParam(required = false) int[] noteIds) {
if (noteIds !=null) {
for (int id : noteIds) {
noteRepository.deleteById(id);
model.addAttribute("delete");
}
}
return "notes/index";
}
Apologies in advance for formatting. I am clearly a novice.
Solution 1:[1]
Replace:
<form th:action="delete" method="post" th:object="${secretNote}">
with:
<form th:action="@{/notes/{id}/delete(id=${secretNote.id})}" method="post" th:object="${secretNote}">
This will add the id of the note in the action URL of the form.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wim Deblauwe |