I want to show a form that has a pre-filled list of objects and each of the object attributes as a field, retrieved from my database using Thymeleaf templates (that the user will then be able to edit). I understand I would use th:each
to accomplish looping over each object in the returned list and creating the pre-filled form fields.
However, if there are no items retrieved from the database, I want to still show a form corresponding to that objects attributes, only with the pre-filled values empty. How would I implement this? I cannot find details in the documentation.
I am assuming you are doing something like this in your controller:
@GetMapping
public String showListOfObjectsForm(Model model) {
List<MyObject> listOfObjects = service.get...
model.addAttribute( "myList", listOfObjects );
return "form"
}
You could check the size of listOfObjects
and add a "dummy" object in the list:
@GetMapping
public String showListOfObjectsForm(Model model) {
List<MyObject> listOfObjects = service.get...
if( listOfObjects.isEmpty() ) {
listOfObjects.add( new MyObject() );
}
model.addAttribute( "myList", listOfObjects );
return "form"
}