I have a pojo class like this
pulic class Role{
private int roleId;
private String roleName;
//default getters setters and constructors
Another POJO class user
public class User{
private String id;
private String name;
private Role role;
// standard getters setters and constructors
My controller class method to call the page
@GetMapping("/adduser")
public String registerUserPage(Model model){
model.addAttribute("roles",roles.listRoles());
User user = new User();
user.setRole(new Role());
model.addAttribute("user",user);
return "adduser";
}
adduser.html
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<form name="registerForm" th:action="@{/createUser}" th:object="${user}" method="POST">
<div><label> First Name : <input type="text" th:field="*{name}"/> </label></div>
<div><label> Id : <input type="text" th:field="*{id}"/> </label></div>
<select th:field="*{role}">
<option value="">Select Test Order</option>
<option th:each="role : ${roles}"
th:value="${role}"
th:text="${role.roleName}"></option>
</select>
<div><input type="submit" value="Add"/></div>
</form>
</body>
</html>
And the createUser controller
@PostMapping("/createUser")
public String registerUser(@ModelAttribute("user") User user, Model model){
System.out.println(digiUser.getName); //this works
System.out.println(digiUser.getRole().getRoleName()); //how??
return "ok";
}
I am able to list roles form the dropdown and also assign other values like name and id successfully. However when I tried to assign the dropdown to the "*{role}", its breaking..
i get the exception:
default message [Failed to convert property value of type 'java.lang.String' to required type 'com.vipin.data.Role' for property 'role';
From the exception i see it casting exception. I know I could probably assign a role Id and later process it however, as there are 2 values in role (roleName and roleId) ,how can I assign the role object directly? Is it possible? any alternative approaches to assign both values of role (id and roleName) form single dropdown selection?