从elaf表单输入值创建arraylist

nwlqm0z1  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(307)

我有一个表单,用于添加用html和thymeleaf编写的产品。

<form th:action="@{/products/get}" th:object="${form}" method="post">
            <div id="fields">
                <label for="name"></label><input type="text" id="name" name="name" autofocus="autofocus" placeholder="NAME" required/><br>
                <label for="label"></label><input type="text" id="label" name="label" autofocus="autofocus" placeholder="LABEL" required/><br>

在窗体下面,有一个按钮,每次按下时都会向窗体添加两个输入字段。新的输入字段与上面的两个输入字段相同。其思想是用户可以使用相同的表单输入任意多个产品的数据。例如,按下按钮一次后,窗体将如下所示:

<form th:action="@{/products/get}" th:object="${form}" method="post">
            <div id="fields">
                <label for="name"></label><input type="text" id="name" name="name" autofocus="autofocus" placeholder="NAME" required/><br>
                <label for="label"></label><input type="text" id="label" name="label" autofocus="autofocus" placeholder="LABEL" required/><br>
                <label for="name"></label><input type="text" id="name" name="name" autofocus="autofocus" placeholder="NAME" required/><br>
                <label for="label"></label><input type="text" id="label" name="label" autofocus="autofocus" placeholder="LABEL" required/><br>

我想使用输入字段中的值创建productform类的arraylist,然后使用@modelattribute将它传递给我的控制器。

public class ProductForm{

    private String name;
    private String label;

//getters and setters
}

然后创建了一个将productform Package 到arraylist中的类

public class ProductFormArray {

ArrayList<ProductForm> forms;
    //getters and setters
}

还有一个控制器

@Controller
@RequestMapping(value = "/products")
public class CreateAccountControllerTemporary {

    @RequestMapping(value = "/get", method = RequestMethod.POST)
    public String createAccount(@ModelAttribute(name = "form")ProductFormArray form){
//some code
}}

我的问题是我不知道如何使用输入字段中的值将对象添加到表单arraylist中?这有可能吗?如何更改我的html文件?

uklbhaso

uklbhaso1#

这当然是可能的,我在《驯服百里香》一书的第361页到第389页对此进行了解释。
你可以在网上免费查阅这本书的来源https://github.com/wimdeblauwe/taming-thymeleaf-sources/tree/main/chapter16
很难将30页总结成一个stackoverflow答案,但简单地说,请查看:
createteamformdata.java:这类似于 ProductFormArray 班级。我确实使用数组而不是数组 ArrayList .

public class CreateTeamFormData {
    @NotBlank
    @Size(max = 100)
    private String name;
    @NotNull
    private UserId coachId;

    @NotNull
    @Size(min = 1)
    @Valid
    private TeamPlayerFormData[] players;

java:这类似于 ProductForm 班级。

public class TeamPlayerFormData {
    @NotNull
    private UserId playerId;
    @NotNull
    private PlayerPosition position;

java:这是使用 CreateTeamFormData .

@GetMapping("/create")
    @Secured("ROLE_ADMIN")
    public String createTeamForm(Model model) {
        model.addAttribute("team", new CreateTeamFormData());
        model.addAttribute("users", userService.getAllUsersNameAndId());
        model.addAttribute("positions", PlayerPosition.values()); //<.>
        return "teams/edit";
    }

    @PostMapping("/create")
    @Secured("ROLE_ADMIN")
    public String doCreateTeam(@Valid @ModelAttribute("team") CreateTeamFormData formData,
                               BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("editMode", EditMode.CREATE);
            model.addAttribute("users", userService.getAllUsersNameAndId());
            model.addAttribute("positions", PlayerPosition.values());
            return "teams/edit";
        }

        service.createTeam(formData.toParameters());

        return "redirect:/teams";
    }

edit.html->这是“thymeleaf”模板。请注意,我使用的是thymeleaf片段 edit-teamplayer-fragment 对于形式中重复自身的部分(因此 name 以及 label (案例中的字段)

<h3>Players</h3>
                           <div class="col-span-6 ml-4">
                               <div id="teamplayer-forms"
                                    th:data-teamplayers-count="${team.players.length}"> <!--.-->
                                   <th:block th:each="player, iter : ${team.players}">
                                       <div th:replace="teams/edit-teamplayer-fragment :: teamplayer-form(index=${iter.index}, teamObjectName='team')"></div>
                                       <!--.-->
                                   </th:block>
                               </div>
                               <div class="mt-4">
                                   <a href="#"
                                      class="py-2 px-4 border border-gray-300 rounded-md text-sm leading-5 font-medium text-gray-700 hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:bg-gray-50 active:text-gray-800"
                                      id="add-extra-teamplayer-form-button"
                                      th:text="#{team.player.add.extra}"
                                      @click="addExtraTeamPlayerForm()"
                                   ></a> <!--.-->
                               </div>
                           </div>

edit-teamplayer-fragment.html:这里是您需要跟踪 index 对于每个片段:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      lang="en">
<!-- tag::main[] -->
<div th:fragment="teamplayer-form"
     class="col-span-6 flex items-stretch"
     th:id="${'teamplayer-form-section-' + __${index}__}"
     th:object="${__${teamObjectName}__}"> <!--.-->
    <!-- end::main[] -->
    <div class="grid grid-cols-1 row-gap-6 col-gap-4 sm:grid-cols-6">
        <div class="sm:col-span-2">
            <div class="mt-1 rounded-md shadow-sm">
                <select class="form-select block w-full transition duration-150 ease-in-out sm:text-sm sm:leading-5"
                        th:field="*{players[__${index}__].playerId}">
                    <option th:each="user : ${users}"
                            th:text="${user.userName.fullName}"
                            th:value="${user.id.asString()}">
                </select>
            </div>
        </div>
        <div class="sm:col-span-2">
            <div class="mt-1 rounded-md shadow-sm">
                <select class="form-select block w-full transition duration-150 ease-in-out sm:text-sm sm:leading-5"
                        th:field="*{players[__${index}__].position}">
                    <option th:each="position : ${positions}"
                            th:text="#{'PlayerPosition.' + ${position}}"
                            th:value="${position}">
                </select>
            </div>
        </div>
        <!-- tag::delete[] -->
        <div class="ml-1 sm:col-span-2 flex items-center text-green-600 hover:text-green-900">
            <div class="h-6 w-6">
                <svg th:replace="trash"></svg>
            </div>
            <a href="#"
               class="ml-1"
               th:text="#{team.player.remove}"
               x-data
               th:attr="data-formindex=__${index}__"
               @click="removeTeamPlayerForm($el.dataset.formindex)"> <!--.-->
            </a>
        </div>
        <!-- end::delete[] -->
    </div>
</div>
</html>

相关问题