I'm trying to implement a create/edit user for my application.
On my controller, I have the following methods to create a new or to edit an existing user.
@RequestMapping(value = "/admin/createUser", method = RequestMethod.GET)
public void createtUser(ModelMap model) throws IOException, Exception {
model.addAttribute("pojo", new UserPojo());
model.addAttribute("roles", initializeProfiles());
}
@ModelAttribute("roles")
public List<UserProfile> initializeProfiles() {
return userProfileService.findAll();
}
@RequestMapping(value = "/admin/createUser", method = RequestMethod.POST)
public String createUserPost(ModelMap model, @Valid @ModelAttribute("pojo") UserPojo pojo, BindingResult result, Errors errors) {
if (errors.hasErrors()) {
System.out.println("There are errors");
return "/admin/createUser";
}
System.out.println(pojo.getProfiles());
try {
userService.save(pojo.getSsoId(),
pojo.getFirstName(),
pojo.getLastName(),
pojo.getEmail(),
pojo.getProfiles(),
pojo.getPassword());
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("success", "User " + pojo.getSsoId() + " has been created successfully");
return "redirect:/admin/homeAdmin";
}
The UserPojo
model is:
public class UserPojo {
private String id;
private String ssoId;
private String firstName;
private String lastName;
private String email;
private String password;
private String state;
private Set<UserProfile> profiles;
// getters and setters
The UserProfile
pojo is:
@Entity
@Table(name="userProfile")
public class UserProfile extends BasePojo {
@Column(name="type", length=15, unique=true, nullable=false)
private String type = UserProfileType.USER.getUserProfileType();
// getter and setter
And the UserProfileType
enum is:
public enum UserProfileType {
USER("USER"),
DBA("DBA"),
ADMIN("ADMIN");
String type;
private UserProfileType(String userProfileType) {
this.type = userProfileType;
}
public String getUserProfileType() {
return type;
}
On my createUser.html
page, I select users with:
<select class="form-control" th:field="*{profiles}" name="profiles" multiple="multiple">
<option th:each="role : ${roles}"
th:value="${{profiles}}"
th:text="${role.type}">
</option>
</select>
Problem is that when I submit data, the controller sees null on the UserPojo
profiles field and does not persist the assigned user profiles.
How to work this out?