0

I want to write a part of a website that lets the user alter the data of a pre existing book. For that, I am trying to use a form which works fine. I just can't figure out how to get the form to display data in the editing fields so the user doesn't have to enter everything again but can simply change some details. My HTML code looks like this:

<form method="post" role="form" class="ui form" id="bookForm" th:action="@{/editBook}" th:object="${bookForm}">
    <div class="field">
        <label for="name">Book</label>
        <input id="name" name="name" th:field="*{name}" th:errorclass="fieldError" type="text" required="required"/><br/>
    </div>

I include some more code about errors and other things but this is basically where I want the form not only to pass values to my java file but also to take values about the book and display them in the editing fields. I think I need to pass the book that the user wants to edit into this form but I'm not sure how. I have tried:

<input type="hidden" id="currentBook" name="currentBook" th:value="${currentBook}"/>

right before the "div" statement and then passing the "currentBook" into HTML with

model.addAttribute("currentBook", currentBook); 

in my @GetMapping method of that website. I then changed the "input" statement in my field as well to

<input id="name" name="name" th:field="*{name}" th:value="${currentBook.name}" th:errorclass="fieldError" type="text" required="required"/><br/>

currentBook.name will give me the name of that book just not within this context. Does anyone know what I'm doing wrong and how it will work?

Thank you in advance!

Corni
  • 33
  • 4
  • You'll have to create Spring MVC controller method with `Model` injected as param and target view name return value. Then you can edit it in `model.addAttribute("currentBook", currentBook)` way and access the attribute later inside the Thymeleaf view. [Spring MVC](https://spring.io/guides/gs/serving-web-content/) – WildDev Nov 24 '18 at 09:46
  • Sorry, I don't quite get what you mean. I have a controller in which I'm using this statement. It looks like this: `@GetMapping("/books") String edits(Model model, BookForm bookForm) { `... Is that what you mean? – Corni Nov 24 '18 at 10:11
  • Yes, but param order matters. It should to be `.edits(BookForm form, Model model)`. For binding the form [@ModelAttribute](https://stackoverflow.com/questions/8688135/modelattribute-annotation-when-to-use-it/26916920#26916920) annotation may be also required – WildDev Nov 24 '18 at 10:14
  • I tried that, also with the @ModelAttribute but it still doesn't work – Corni Nov 24 '18 at 10:43

0 Answers0