Skip to content
Advertisement

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.

Advertisement

Answer

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.

Advertisement