I am playing around with Thymeleaf and have created a dropdown menu with people's names on it. My controller class represents a single user, which also has a sibling name with the user.
When making the form, in Thymeleaf, the th:field="*{sibling}"
is causing my issue and I am unable to resolve this.
I have looked at SO links such as this one , however this did not help me to fix my problem.
Directly below is the stack trace of the error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.thymeleaf.spring4.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:401) ~[thymeleaf-spring4-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.spring4.util.FieldUtils.getBindStatus(FieldUtils.java:328) ~[thymeleaf-spring4-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.spring4.util.FieldUtils.getBindStatus(FieldUtils.java:294) ~[thymeleaf-spring4-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at
........
This is the code that I have produced, so far, which has currently been unsuccessful. The SO post I followed suggested that I include BindingResult
but even with that, still no luck.
I feel like I am missing something somewhat obvious but cannot think of a solution!
EDIT: Following bphilipnyc's advice, I have added user object to the model in my controller, which allows the dropdown list to render. However, the dropdown list does not populate at all.
@Document(collection = "users")
public class User {
@Id
private String id;
private String userName;
private String sibling;
//getters and setters below
}
My Controller looks like this:
@Controller
public class UserController {
@Autowired
private UserService userService;
Set<String> allSiblings = new HashSet<>();
@ModelAttribute("user")
public Recipe defaultInstance() {
User user = new User();
return user;
}
@GetMapping("/")
public String index(Model model){
List<User> allUsers = userService.findAll();
createDropDown();
model.addAttribute("users", allUsers);
model.addAttribute("allSiblings", this.allSiblings);
return "index";
}
@GetMapping("/search")
public String search(@Valid @ModelAttribute("user") User user, BindingResult bindingResult){
if(bindingResult.hasErrors()){
System.out.println("There was a error "+bindingResult);
return "index";
}
System.out.println(user.getSibling());
return "result";
}
private void createDropDown(){
allSiblings.add("john");
allSiblings.add("paul");
}
And finally I have an index.html page which has the following thymeleaf dropdown form:
<form style="display:inline-block" th:action="@{/search}" th:object="${user}">
<select th:field="*{sibling}">
<option value=""> --</option>
<option th:each="ing : ${allSiblings}"
th:value="${ing}"
th:utext="${ing}">
</option>
</select>
<button type="submit">submit</button>