简体   繁体   中英

How to pass two objects to use in a form using thymeleaf?

My problem is the following:

I've 2 differents objects that I've to fill from a single form.

With 1 object, I simply do in the newFoo.html:

<form th:object="${foo}" th:action="@{/foo}" method="post">
    <input type="text" th:field="*{name}"/>
    <button type="submit">Go</button>
</form>

and in the FooController:

@RequestMapping(value = "/foo/new", method = RequestMethod.GET) 
public String newFoo(final Foo foo, Model model) { 
    return "newFoo"; 
} 

@RequestMapping(value = "/foo/new", method = RequestMethod.POST) 
public String saveFoo(final Foo foo, final BindingResult bindingResult, Model model) { 
    fooService.save(foo); 
    return "redirect:/foo/new"; 
} 

Let's say I've an other object bar with a "status" variable in it. How can I do to pass that object so I can submit the input within the same form?

Like:

<form th:object="${foo} && ${bar}" th:action="@{/foo}" method="post">
    <input type="text" th:field="*{name}"/>
    <input type="text" th:field="*{status}"/>
    <button type="submit">Go</button>
</form>

So far I tried to do with to fieldset with a th:object in it, that doesn't work, I tried to put two th:object in the form, that doesn't work either.

The only way I found is to build an other object containing those two objects, and pass it. That works well, but I can't create that kind of object, it's nonsense (even if it works).

Of course, the objects aren't as simple as Foo and Bar here, otherwise I would have merge those two. But that's not something I can do.

Is it even possible to pass two objects like that to use in a form?

Thanks already.

I don't think you need to use two th:objects . Just use th:value

<form th:action="@{/foo}" method="post">
      <input type="text" th:value="${foo.name}" name="name"/>
      <input type="text" th:value="${bar.status}" name="status"/>
      <button type="submit">Go</button>
</form>

I would think Spring is smart enough, on the controller side, to use its mapping techniques to map your fields to their proper command object, foo or bar.

i used a div tag to surround the form input for my second object and added a th:object..... the controller processed it and added it to the database.

<form method=post th:object="${object1}" >
   <div th:object="${object2}" >

      code......

   </div> 
   <input type="submit" />
</form>

I think the most elegant way to accomplish your result is reported here: Adding multiple objects with the same name fields using Thymeleaf/Spring Boot

The other solutions work if the two objects do not have fields with the same name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM