Form for each object in list - ThymeLeaf

Viewed 324

I am trying to make for each object in my list modal that contains a form with that object data.

So I have in my controller:

model.addAttribute("eventsInList", eventsInList);

and in my ThymeLeaf template:

<div th:each="evnt,intr : ${eventsInList}">
   <div class="modal fade" th:id="'modal-' + ${evnt.getId()}">
     // some content
      <form th:action="@{/updateEvent}" th:object="${evnt}" method="POST">
         <input type="text" class="form-control pull-right datepicker"
                           th:value="${evnt.getDate()}"
                           th:field="*{date}">
      </form>
   </div>
</div>

When I run this code it throws:

Neither BindingResult nor plain target object for bean name 'evnt' available as request attribute


So I tried this:

controller:

model.addAttribute("eventsInList", eventsInList); // list of CalendarEvent
model.addAttribute("editEvent", new CalendarEvent());

ThymeLeaf template:

<div th:each="evnt,intr : ${eventsInList}">
   <div class="modal fade" th:id="'modal-' + ${evnt.getId()}">
     // some content
      <form th:action="@{/updateEvent}" th:object="${editEvent}" method="POST">
         <input type="text" class="form-control pull-right datepicker"
                           th:value="${evnt.getDate()}"
                           th:field="*{date}">
      </form>
   </div>
</div>

This case does not throw any exception, but th:value="${evnt.getDate()}" is null

And confusing for me is that the row <div class="modal fade" th:id="'modal-' + ${evnt.getId()}"> normally works.

So is there any solution for this problem?

Thanks for your help all :)

1 Answers

After a few hours, I made it!

So here is my solution (works for me):

my controller:

model.addAttribute("eventsInList", eventsInList); // list of CalendarEvent

my ThymeLeaf template:

<div th:each="evnt, intr : ${eventsInList.getEvents()}">
   <div class="modal fade" th:id="'modal-' + ${evnt.getId()}">
     // some content
      <form th:action="@{/updateEvent}" th:object="${eventsInList[__${intr.index}__]}" method="POST">
         <input type="text"
                th:value="${eventsInList[__${intr.index}__].getDate()}"
                th:name="|date|">
      </form>
   </div>
</div>

As you can see I didn't use th:field="" it's because in this case the th:field does not work, but there is another solution to bind input with th:object and that is that you can use th:name which bind input value with th:object.

For more info, you can read this

Related