Im trying push object into List im able to push value to normal fields, Following is the code for binding value i have used: Job Model
public class Job {
public Job(String name) {
super();
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Candidate Model
public class Candidate {
private String candidatename;
private List<Job> jobs;
public String getCandidatename() {
return candidatename;
}
public void setCandidatename(String candidatename) {
this.candidatename = candidatename;
}
public List<Job> getJobs() {
return jobs;
}
public void setJobs(List<Job> jobs) {
this.jobs = jobs;
}
}
candidatedetail.html
<form class="form-horizontal" th:action="@{/savejobhistory}" method="post" th:object="${candidate}">
<label>Candidate name:</label>
<input type="text" th:field="*{candidatename}" /><br/>
<button type="submit" class="btn btn-default">Submit</button>
</form>
candidatejob.html
<h2>Candidate Details!</h2>
<span>Note:</span><span th:text="${candidate.candidatename}"></span><br/>
Controller.java
@GetMapping("/emp")
public String test(Model model) {
Candidate candidate = new Candidate();
model.addAttribute("candidate", candidate);
return "candidatedetail";
}
@PostMapping("/savejobhistory")
public String sendForm(@ModelAttribute("candidate") Candidate candidate) {
System.out.println("Inisde Meth");
System.out.println(candidate.getCandidatename());
return "candidatejob";
}
how to push to list i tried following and failed
<input type="text"
placeholder='Company Name' class="form-control" th:field="*{candidate.jobs}" th:value="${job.name}"/></td>
<label th:text="${job.name}"></label>
CodePudding user response:
You can use for each using the following format as an example :
<tr th:each="Jobs : ${yourJobList}">
<td><span th:text="${job.yourjobfield1}"></span></td>
<td><span th:text="${job.yourjobfield2}"></span></td>
</tr>
This will multiply the above block of elements for each job in your list.
CodePudding user response:
This tutorial can help explain how to index into an array when using a form. th:field="*{jobs[${0}].name}"
is incorrect. If you want to specify the index it should look like this:
th:field="*{jobs[0].name}"
or if you want to use a variable:
th:field="*{jobs[__${variable}__].name}"
(you must use double underscores __
to do preprocessing in this case.)