Reputation: 23
this is my first question here so please be kind :D
I am in the middle of a UNI project which is a businesses scheduler. I want to be able to add many task groups to my project, so I decided to do it with dropdown in a loop. Every time someone clicks on button new dropdown appears (not sure if it's best solution, but I'am still learning Spring and Thymeleaf). The problem is that when I have only one dropdown everything is fine.
But after I click on plus button the options from dropdown disappears.
I tried to find the answer on the internet but I can't find anything similar.
Here is my form code:
<form action="#" method="post" th:action="@{/projects}" th:object="${project}">
<p class="C(red)" th:if="${#fields.hasAnyErrors()}" th:errors="*{all}"></p>
<br/>
<div><h2>New project</h2></div>
<label>Description
<input type="text" class="form-control" th:field="*{description}" th:errorclass="'Bdc(red)'"/>
</label>
<fieldset th:each="projectGroup, projectGroupStat : *{selectedGroups}">
<div class="btn-group">
<select class="dropdown" th:field="*{selectedGroups[__${projectGroupStat.index}__]}"
th:id="${projectGroupStat.index}">
<option th:each="group: ${groups}" th:value="${group.id}"><a class="dropdown-item"
th:text="${group.description}"/>
</option>
</select>
</div>
</fieldset>
<div>
<button type="submit" name="addGroup">+</button>
</div>
<br/>
<p>
<button type="submit" class="btn btn-primary">Add</button>
<button type="reset" class="btn btn-warning">Clear</button>
</p>
</form>
Here is a part of my controller code:
@GetMapping(produces = MediaType.TEXT_HTML_VALUE)
String showProjects(Model model){
model.addAttribute("project", new ProjectWriteModel());
model.addAttribute("groups", getGroups());
return "projects";
}
@PostMapping(params = "addGroup")
String addProjectGroup(@ModelAttribute("project") ProjectWriteModel current){
current.getSelectedGroups().add(new String());
return "projects";
}
private List<GroupReadModel> getGroups() {
return taskGroupService.readAll();
}
Am I missing something here? I will be grateful for any help. Thank you!
Upvotes: 1
Views: 225
Reputation: 6242
This is what I could figure out from the limited code that you have provided.
In the addProjectGroup
you need to set the groups
in the Model
. Like:
model.addAttribute("groups", getGroups());
the same way that you did in the method showProjects
. So this way it will be available to your HTML.
Upvotes: 1