Adding Rows

Learn how to dynamically add new rows using JavaScript so that no page refreshes are needed.

Re-use fragments

Ideally, we want to reuse the fragment we’ve already used for generating the page. This will ensure that the layout and functionality of the rows that are generated at page render are exactly the same as the rows we add dynamically. To make it possible to reuse the fragment, we have to alter it slightly:

Press + to interact
<div th:fragment="teamplayer-form"
class="col-span-6 flex items-stretch"
th:id="${'teamplayer-form-section-' + __${index}__}"
th:object="${__${teamObjectName}__}">

On line 4, there’s an extra th:object attribute.

We’ll need to add an extra parameter teamObjectName that will tell the fragment the name of the TeamFormData binding object in the Model. When rendering normally, this will be the name of the th:object we already have on the full form in teams/edit.html. When Thymeleaf needs to render the fragment alone, we will need to pass in a dummy object there. Otherwise, Thymeleaf will not be able to ...