0

I'm wondering how I can receive the object from frontend(Thymeleaf) using @ModelAttribute. Main purpose of this is to edit object in the new view(html) where the fields are filled updated object therefore the invoice object is passed to model for further editing.

I tried to do that.

Model

public class Invoice {
    private Long id;
    private BigDecimal price;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate date;
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public LocalDate getDate() {
        return date;
    }

    public void setDate(LocalDate date) {
        this.date = date;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
    @GetMapping("/edit")
    public String editInvoice(Model model, @ModelAttribute Invoice invoice){
        model.addAttribute("updatedInvoice", invoice);
        return "edit";
    }
<tr th:each="invoice:${allInvoices}">
        <td th:text="${invoice.id}"></td>
        <td th:text="${invoice.price}"></td>
        <td th:text="${invoice.date}"></td>
        <td th:text="${invoice.name}"></td>
        <td><a th:href="@{/delete(id=${invoice.id})}" class="btn btn-danger">DELETE</a></td>
        <td><a th:href="@{/edit(invoice=${invoice})}" class="btn btn-primary">EDIT</a></td>
    </tr>

Finally I see that the invoice object has allocated memory but it is empty(I mean its variables) When I printout the invoice object I get this: main.domain.model.Invoice@37567a3b it is not null but object has empty variables.

Thank you in advance for support and help.

Main purpose of this is to edit object in the new view(html) where the fields are filled updated object therefore the invoice object is passed to model for further editing.

m19v
  • 1,800
  • 4
  • 11
  • 26
NeQ
  • 1
  • 1
    You might want to read up on [Form handling with Thymeleaf](https://www.wimdeblauwe.com/blog/2021/05/23/form-handling-with-thymeleaf/). – Wim Deblauwe Oct 26 '22 at 06:42
  • Hi&Welcome! Passing an "object via get" (which ` – xerx593 Oct 26 '22 at 14:42
  • ..whereas on controller, you could try just: `@GetMapping("/edit") public String editInvoice(Invoice invoice){..` – xerx593 Oct 26 '22 at 14:45
  • For the "edit" a `POST` (or even `PATCH` http request) would be more appropriate, you can achieve, by wrapping each row with a `
    ...` ..while the button would rather "form.submit()"
    – xerx593 Oct 26 '22 at 14:50
  • For (use case) "delete", (http request) `DELETE` "sounds super"!:) – xerx593 Oct 26 '22 at 14:52

0 Answers0