2017-05-23 2 views
0

Ich habe eine Form bekommt:Thymeleaf passiert Set Objekt als Mitglied des Objekts Controller

<form action="#" th:action="@{/private/createUser}" th:object="${toCreate}" method="post"> 

<label for="alias">User Alias</label> 
<input id="alias" type="text" th:field="*{alias}"/> 

<label for="fullName">Full Name</label> 
<input id="fullName" type="text" th:field="*{fullName}"/> 

<label for="password">Password</label> 
<input id="password" type="password" th:field="*{password}"/> 

<ul for="userRoles"> 
    <li th:each="role, roleStat : ${availableRoles}"> 
    <div> 
     <label th:for="${roleStat.count}" th:text="${role.name}">Role Name</label> 
     <input th:id="${roleStat.count}" type="checkbox" th:value="${role}"/> 
    </div> 
    </li> 
</ul> 

<button type="submit" th:text="Submit" name="submitButton"></button> 

</form> 

, die angeblich ist ein User-Objekt zu meinem Controller zur Verfügung zu stellen:

@Controller 
public class UserCreationController { 

    @Autowired 
    UserService userService; 

    @RequestMapping(value = "/private/createUser", method = RequestMethod.GET) 
    public String createUser(Model m) { 
     m.addAttribute("availableRoles", UserRole.values()); 

     m.addAttribute("toCreate", new User()); 

     return "createUser"; 
    } 

    @RequestMapping(value = "/private/createUser", method = RequestMethod.POST) 
    public String createUserPost(@ModelAttribute("toCreate") User toCreate, Model m, HttpServletResponse response) { 
     FlexibleResponse resp = userService.createUser(toCreate); 
     if (resp.isPositive()) { 
      m.addAttribute("success", resp.getContent()); 
     } else { 
      m.addAttribute("failure", resp.getContent()); 
     } 

     response.setStatus(resp.isPositive() ? 200 : HttpServletResponse.SC_BAD_REQUEST); 
     return "redirect:createUser"; 
    } 
} 

Alles funktioniert reibungslos, außer für die "userRoles", die eine Set<UserRole> userRoles; UserRole ist eine enum (Sie können wahrscheinlich durch den Blick auf den Controller zu erkennen). Was muss ich tun, um diese Checkboxen als Set in meine th:object="${toCreate}" zu binden?

Antwort

1

Sie fehlen th:field für die Rolle Checkbox-Eingabe. Ohne es wird das erforderliche name Attribut nicht generiert. Versuchen Sie folgendes:

<label th:for="${#ids.next('userRoles')}" th:text="${role.name}">Role Name</label> 
<input type="checkbox" th:field="*{userRoles}" th:value="${role}"/> 

Referenz: Checkbox fields Abschnitt in Thymeleaf Tutorial.

Verwandte Themen