Thymeleaf retrieving text from input with similar field name adding it to another separated by comma

huangapple go评论66阅读模式
英文:

Thymeleaf retrieving text from input with similar field name adding it to another separated by comma

问题

我寻求帮助是因为Thymeleaf表现出奇怪的行为:
这是我的表单:

<form action="#" th:action="@{/add-new-board}" method="post">

    <p>Board name: <input type="text" th:name="board" th:field="${board.name}" /></p>
    <p th:if="${#fields.hasErrors('board.name')}" th:errors="${board.name}">Name Error</p>

    <p>Section #1 name: <input type="text" th:name="section" th:field="${section.name}" /></p>
    <p th:if="${#fields.hasErrors('section.name')}" th:errors="${section.name}">Name Error</p>

    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>

这是我的控制器:

@GetMapping(path = "/add-new-board")
public String addNewBoardForm(Model model) {
    model.addAttribute("board", new Board());
    model.addAttribute("section", new Section());
    return "fragments/forms/add-new-board";
}

@PostMapping(path = "/add-new-board")
public String addNewBoardSubmit(@Valid @ModelAttribute Board board,
                                @Valid @ModelAttribute Membership membership,
                                @Valid @ModelAttribute Section section,
                                @AuthenticationPrincipal UserDetailsImpl principal,
                                BindingResult result,
                                RedirectAttributes attributes) {
    if (result.hasErrors()) {
        attributes.addFlashAttribute("create_board_fail", "Check if you have all fields");
        return "fragments/forms/add-new-board";
    } else {
        board.setCreated_at(LocalDateTime.now());
        Slugify slug = new Slugify();
        board.setSlug(slug.parse(board.getName()));
        boardRepository.save(board);

        User user = userRepository.findByEmail(principal.getEmail()).get();
        membership.setMember_type(MemberType.MANAGER);
        membership.setBoardId(board);
        membership.setUserId(user);
        membershipRepository.save(membership);

        section.setBoard(board);
        section.setColor(ColorType.BLUE_BASIC);
        section.setOrdering(1);
        sectionRepository.save(section);

        attributes.addFlashAttribute("create_board_success", "You successfully added a new board!");
        return "redirect:/";
    }
}

所以,我的目标是将来自第一个输入的文本插入到“board”表中的“name”列,并将来自第二个输入的文本插入到“section”表中的“name”列。因此,这两个列的标题是相似的。现在,当我运行代码,填写输入并提交后,我到达了我的数据库:

数据库表图片

在这里,“AAA”是我在第一个输入框中写的内容,“BBB”是我在第二个输入框中写的内容。

英文:

I'm asking for help because thymeleaf does somthing weird:
Here is my form:

&lt;form action=&quot;#&quot; th:action=&quot;@{/add-new-board}&quot; method=&quot;post&quot;&gt;
&lt;p&gt;Board name: &lt;input type=&quot;text&quot; th:name=&quot;board&quot; th:field=&quot;${board.name}&quot; /&gt;&lt;/p&gt;
&lt;p th:if=&quot;${#fields.hasErrors(&#39;board.name&#39;)}&quot; th:errors=&quot;${board.name}&quot;&gt;Name Error&lt;/p&gt;
&lt;p&gt;Section #1 name: &lt;input type=&quot;text&quot; th:name=&quot;section&quot; th:field=&quot;${section.name}&quot; /&gt;&lt;/p&gt;
&lt;p th:if=&quot;${#fields.hasErrors(&#39;section.name&#39;)}&quot; th:errors=&quot;${section.name}&quot;&gt;Name Error&lt;/p&gt;
&lt;p&gt;&lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt; &lt;input type=&quot;reset&quot; value=&quot;Reset&quot; /&gt;&lt;/p&gt;
&lt;/form&gt;

Here is my controller:

@GetMapping(path = &quot;/add-new-board&quot;)
public String addNewBoardForm(Model model) {
model.addAttribute(&quot;board&quot;, new Board());
model.addAttribute(&quot;section&quot;, new Section());
return &quot;fragments/forms/add-new-board&quot;;
}
@PostMapping(path = &quot;/add-new-board&quot;)
public String addNewBoardSubmit(@Valid @ModelAttribute Board board,
@Valid @ModelAttribute Membership membership,
@Valid @ModelAttribute Section section,
@AuthenticationPrincipal UserDetailsImpl principal,
BindingResult result,
RedirectAttributes attributes) {
if (result.hasErrors()) {
attributes.addFlashAttribute(&quot;create_board_fail&quot;, &quot;Check if you have all fields&quot;);
return &quot;fragments/forms/add-new-board&quot;;
} else {
board.setCreated_at(LocalDateTime.now());
Slugify slug = new Slugify();
board.setSlug(slug.parse(board.getName()));
boardRepository.save(board);
User user = userRepository.findByEmail(principal.getEmail()).get();
membership.setMember_type(MemberType.MANAGER);
membership.setBoardId(board);
membership.setUserId(user);
membershipRepository.save(membership);
section.setBoard(board);
section.setColor(ColorType.BLUE_BASIC);
section.setOrdering(1);
sectionRepository.save(section);
attributes.addFlashAttribute(&quot;create_board_success&quot;, &quot;You successfully added a new board!&quot;);
return &quot;redirect:/&quot;;
}

So, my goal is to insert text from 1st input to "board" table to a column "name", and insert text from 2nd input to "section" table to a column "name". So this column titles are similar. Now when I run code, fill inputs and submit it, I'm getting to my database:

database tables img

Where "AAA" is what I wrote in 1st input, and "BBB" in 2nd

答案1

得分: 2

这是因为您错误地使用了 th:fieldth:field 的设计是与单个 th:object 一起使用的,但目前您正在使用两个不同的对象 boardsection。在渲染 HTML 时,这两个输入字段可能都有相同的 name=&quot;name&quot;,并且在提交时,这些值会被连接在一起,从而导致您所看到的行为。

您应该将 Board 和 Section 添加到一个单独的对象中,并将其用作表单。例如,如果您创建了一个 BoardForm 对象:

public class BoardForm {
  private Board board = new Board();
  private Section section = new Section();

  // Getters and setters...
}

然后将其添加到您的模型中:

model.addAttribute("form", new BoardForm());

接下来,您的 HTML 代码将如下所示:

<form action="#" th:action="@{/add-new-board}" th:object="${form}" method="post">
    <p>Board name: <input type="text" th:name="board" th:field="*{board.name}" /></p>
    <p>Section #1 name: <input type="text" th:name="section" th:field="*{section.name}" /></p>
    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
英文:

This is happening because you are using th:field incorrectly. th:field is designed to be used with a single th:object but right now you are using 2 different objects board and section. When the HTML is rendered, both inputs probably have the same name=&quot;name&quot; and when that is submitted, the values are concatenated together and you get the behavior you are seeing.

You should instead add Board and Section to a single object, and use that as your form. For example, if you created a BoardForm object:

public class BoardForm {
private Board board = new Board();
private Section section = new Section();
// Getters and setters...
}

added that to your model instead

model.addAttribute(&quot;form&quot;, new BoardForm());

then your html would look like this

&lt;form action=&quot;#&quot; th:action=&quot;@{/add-new-board}&quot; th:object=&quot;${form} method=&quot;post&quot;&gt;
&lt;p&gt;Board name: &lt;input type=&quot;text&quot; th:name=&quot;board&quot; th:field=&quot;*{board.name}&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Section #1 name: &lt;input type=&quot;text&quot; th:name=&quot;section&quot; th:field=&quot;*{section.name}&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt; &lt;input type=&quot;reset&quot; value=&quot;Reset&quot; /&gt;&lt;/p&gt;
&lt;/form&gt;

huangapple
  • 本文由 发表于 2020年5月4日 03:19:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/61580315.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定