as the title says i wanna know how to implement that functionality in this project. I'm new at this Spring and Thymeleaf topic using the CrudRepository, Entities, the services for each repository and their controller.
In resume, i want to populate the district select box by the selected value of the nation select box and keep the selected value of the first nation select box.
Here's the code snippets:
LocationController.java:
@Controller
public class LocationController {
@Autowired
private NationService nationService;
@Autowired
private DistrictService districtService;
@GetMapping("/location")
public String init(Model model){
model.addAttribute("nations", nationService.findAll());
return "location";
}
@PostMapping("/setDistricts")
public String setDistricts(Model model, @RequestParam long id){
model.addAttribute("districts", districtService.findAllByNation(id));
return "location";
};
}
Nation.java: (Entity)
@Entity
public class Nation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "nation")
private String nation;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
}
District.java: (Entity)
@Entity
public class District {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "district")
private String district;
@ManyToOne
private Nation nation;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public Nation getNation() {
return nation;
}
public void setNation(Nation nation) {
this.nation = nation;
}
}
location.html:
<div class="form-group">
<label for="nation"></label>
<select class="custom-select" id="nation">
<th:block th:each="nation: ${nations}" th:onchange="@{/setDistricts(id=${nation.id})}">
<option th:value="${nation.id}" th:text="${nation.nation}"></option>
</th:block>
</select>
</div>
Grateful for your attention