I'm using thymeleaf to spit out cards for all of the objects in a list but I want the user to be able to click a button on one of these cards and then let my backend know which card (baseElement.name
) has been selected by sending back the name of the baseElement
. This is working great with a dropdown menu instead of cards but I would much rather use cards for user experience.
In debug mode I see that selectedElementName
comes back as empty string, so where I'm trying to fill it with baseElement.name
doesn't seem to be working.
View:
<th:block th:each="baseElement : ${baseElements}">
<div >
<form method="post"
th:action="@{/account/baseElementLevel}" th:object="${selectedElementName}">
<div >
<div >Base Element</div>
<div >
<div >
<h5 name="selectedElementName" id="selectedElementName" th:value="${baseElement.name}" th:text="${baseElement.name}"></h5>
<p th:text="${baseElement.briefDescription}"></p>
<button type="submit">Enter</button>
</div>
</div>
<div >Entry Points:</div>
</div>
</form>
</div>
</th:block>
Controller:
@RequestMapping(value = "/baseElementLevel", method = RequestMethod.GET)
public String baseElementLevel(Model model, Principal principal) {
User user = userService.findByUsername(principal.getName());
List<BaseElement> baseElements = elementService.findByUserUserIdAndType(user.getUserId(), "BASE");
model.addAttribute("baseElements", baseElements);
model.addAttribute("selectedElementName", "");
model.addAttribute("baseElement", "");
model.addAttribute("amount", "");
return "baseElementLevel";
}
@RequestMapping(value = "/baseElementLevel", method = RequestMethod.POST)
public String baseElementLevelPOST(@ModelAttribute("amount") String amount,
@ModelAttribute("selectedElementName") String selectedElementName, Principal principal) {
User user = userService.findByUsername(principal.getName());
user.setSelectedBaseElement(
elementService.findByNameAndUserUserId(selectedElementName, user.getUserId()).getId());
userService.save(user);
return "redirect:/account/elementView";
}
I'm trying to display a list of elements so that each gets a card which displays the element's information and then a button on each card to post and tell the controller which card the user selected.
I can get it to work just fine if I replace cards with a select drop down but not sure how to get this lined up with cards for each list item.
Thank you for your help.
CodePudding user response:
<h5 />
s don't get submitted when you submit a form. you could use a hidden form element for this:
<div >
<h5 th:text="${baseElement.name}" />
<input type="hidden" name="selectedElementName" th:value="${baseElement.name}" />
<p th:text="${baseElement.briefDescription}" />
<button type="submit">Enter</button>
</div>