具有默认值的Thymeleaf表单数组

时间:2020-03-02 10:59:24

标签: spring forms thymeleaf

我正在使用Spring + Thymeleaf来查看和修改数据库中的用户。我想将输入字段设置为原始用户的实际值,但是我尝试使用不同的样式,但它不起作用。

使用当前配置,我可以更新用户信息并查看原始用户的ID(不在输入字段中),但是默认情况下我无法在输入字段中显示实际配置。

控制器:

@GetMapping(value = {"/", ""})
public String subusersPage(HttpSession session, Model model) {
    String idUser = BaseController.getLoggedUser(session);
    UserDTO userDTO = userService.getUserById(idUser);
    model.addAttribute("subusersDTO", userService.getSubusersDTO(userDTO.getSubusers()));
    model.addAttribute("populations", userDTO.getPopulations());
    model.addAttribute("configurations", userDTO.getConfigurations());
    model.addAttribute("attributes", userDTO.getAttributes());
    model.addAttribute("subuserDTO", new SubuserDTO());
    return "subusers";
}

HTML:

<th:block th:each="subuserDTO_original : ${subusersDTO}">
    <hr>
    <form action="#" th:action="@{/subusers/__${subuserDTO_original.id}__}" th:object="${subuserDTO}" method="post">
        <div>
            <p th:text="${'Id: ' + subuserDTO_original.id}"></p>
            <p>Name:            <input type="text" th:field="*{name}"           th:name="name"          th:value="${subuserDTO_original.name}"/></p>
            <p>Population:      <input type="text" th:field="*{population}"     th:name="population"    th:value="${subuserDTO_original.population}"/></p>
            <p>Configuration:   <input type="text" th:field="*{configuration}"  th:name="configuration" th:value="${subuserDTO_original.configuration}"/></p>
            <p>Attributes:      <input type="text" th:field="*{attributes}"     th:name="attributes"    th:value="${subuserDTO_original.attributes}"/></p>
            <p>
                <button type="submit" th:name="action" th:value="update">Update</button>
                <button type="submit" th:name="action" th:value="delete">Delete</button>
                <button type="reset" th:name="action" th:value="clear">Clear</button>
            </p>
        </div>
    </form>
    <form action="#" th:action="@{/subusers/__${subuserDTO_original.id}__}" method="get">
        <button type="submit">Default</button>
    </form>
</th:block>

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:0)

如果要编辑现有用户,则需要使用原始用户的值填充th:object(在这种情况下为${subuserDTO})。这是因为当您使用属性th:field="*{name}"时,它实际上会覆盖html标签的nameidvalue(这就是th:value="${subuserDTO_original.name}"没有工作。

您可以执行的另外两个选择:

  1. 您还可以设置name="name"并改用th:value
  2. 或其他选择,您可以将${subuserDTO_original}用作th:object
相关问题