【问题标题】:Thymeleaf form array with default values具有默认值的 Thymeleaf 表单数组
【发布时间】:2020-06-14 16:01:35
【问题描述】:

我正在使用 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>

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

【问题讨论】:

    标签: spring forms thymeleaf


    【解决方案1】:

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

    你可以做的另外两个选择:

    1. 您也可以设置name="name" 并改用th:value
    2. 或者其他选项,您可以使用${subuserDTO_original} 作为您的th:object

    【讨论】:

    • 非常感谢!感谢您的评论,我意识到您可以用idname 替换th:field 标签,并且它们的行为方式相同,而不会覆盖value 标签。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 2016-12-13
    • 2012-11-27
    • 1970-01-01
    相关资源
    最近更新 更多