Home > Mobile >  how to bind form data to list<object>
how to bind form data to list<object>

Time:08-02

ResizeDTO

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResizeDTO {
    private String group_id;
    private String width;
    private String height;
}
View(thymeleaf)

<form action="resize" method="post">
    <div th:each="m : ${list}">
        <input type="text" name="group_id" required>
        <input type="text" name="width" required>
        <input type="text" name="height" required>
</div>
</form>
Controller

@GetMapping("/config/resize")
    public String Config_Resize(@RequestParam(required = false) String group_id, Model model){
        model.addAttribute("group_id", group_id);
        return "config/resize";
    }
@PostMapping("/config/resize")
    public String Config_Resize_Update(ResizeDTO resizeDTOList){
        resizeService.updateResize(resizeDTOList);
        return "redirect:resize";
    }

i want to bind data for 'list' like ResizeDTO(group_id=id1, width=1024, height=720), ResizeDTO(group_id=id2, width=2560, height=1440), ResizeDTO(group_id=id3, width=1080, height=860)

how can i do?

CodePudding user response:

You have to change field names of the input to include indexes [x] like so

<div th:each="listItem, iter : ${list}">
    <input type="text" th:field="${list[__${iter.index}__].group_id}" required>
    <input type="text" th:field="${list[__${iter.index}__].width}" required>
    <input type="text" th:field="${list[__${iter.index}__].height}"  required>
</div>

See this article for more info about working with list in thymeleaf https://www.baeldung.com/thymeleaf-list#list-selection-expression

  • Related