I have 2 entity classes named District and Street, in View, to form is assigned Street object. How can I bind value of Street.district.id ? On for submitting I get NullPointerException .
View entities and form:
<form class="form-inline" action="#" th:action="@{/direct/api/v1/newStreet}" th:object="${street}" method="POST">
<div class="form-group">
<label for="name">Name</label>
<input type="text" th:field="*{name}" class="form-control" id="name" placeholder="Street name"/>
</div>
<div class="form-group">
<label for="district">District</label>
<select class="form-control" id="district">
<option th:each="d : ${districts}" th:field="*{district.id}" th:value="${d.id}" th:text="${d.name}"></option>
</select>
</div>
<button type="submit" class="btn btn-default">Save</button>
Controller:
@RequestMapping(value = "/newStreet", method = RequestMethod.POST)
public String newStreet(@ModelAttribute Street street){
log.info(street.getName());
log.info(String.valueOf(street.getDistrict().getId()));
return "redirect:/streets";
}
On form submitting I get Street name from input and null District.
Your error is in the select.
The attribute
th:field="*{district.id}"
should be in the select not in the option tag
Result:
<select class="form-control" id="district" th:field="*{district.id}">
<option th:each="d : ${districts}" th:value="${d.id}" th:text="${d.name}"></option>
</select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.