How to bind an object to a form (th:object) using th:each for a list of objects with Thymleaf

元气小坏坏 提交于 2020-05-16 03:26:33

问题



Im trying to create a loop using th:each on a list object and so creating like 10 forms binding different objects. As far without success.. is it even possible? if not.. do you have an idea how to dynamically bind an object to forms in a similar way for objects in a list? This is what i tried..

@RequestMapping(value = "/area")
    public String index(@AuthenticationPrincipal User currentUser, Model model) {

        /* getPersons() returns an object list of diferent persons */
        model.addAttribute("personslist", currentUser.getPersons());

        return "area";
    }

Thymleaf / html:

<div th:each="person: ${personslist}">           
     <form th:object="${person}" th:action="@{/fooBar}" method="post">
          <input hidden="hidden" th:field="${person.id}"/>
            //Other input fields...
           <button type="submit"></button>
     </form>
</div>

回答1:


I'm not sure if that is what you are trying to do but you can submit a list of persons as an object in one form instead of looping through the forms. You just have to create a wrapper class for your list of persons and use that wrapper class object as an object in your form.

    <form th:object="${personslistWrapper}" th:action="@{/fooBar}" method="post">

            // Looping through the persons on the list for each input field

           <button type="submit"></button>
     </form>

Check out this post for details on that: How to bind an object list with thymeleaf?



来源:https://stackoverflow.com/questions/53787332/how-to-bind-an-object-to-a-form-thobject-using-theach-for-a-list-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!