Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...