Home > OS >  Cant insert data from dropdown menu in table from thymeleaf but can in MySQL manually
Cant insert data from dropdown menu in table from thymeleaf but can in MySQL manually

Time:12-29

On the page, I have a form that, among other things, in addition to fields for entering amounts, notes, and dates, also has a drop-down menu that allows the user to choose one item from the list. That dropdown menu is populated from the database and that works fine. Now, when user choose one item from the list and click on save button to insert his choices into database, that field is null in the table, other fields are saved fine but that field from dropdown menu is not saved, its NULL. But, I can go in MySQL and manually assign category to that field, see picture below.

Its like this after user click on save:

enter image description here

But I can assignee manually that field from MySQL, as you can see:

enter image description here

This is thymeleaf code:

<form action="#" th:action="@{/api/transaction/saveTransaction/{walletId} (walletId=${id})}"
      th:object="${transaction}" method="POST">
    <input type="text" th:field="*{amount}" placeholder="Enter amount" >

    <input type="text" th:field="*{note}" placeholder="Enter note" >
    <input type="date" th:field="*{date}" >
    <select  id="dropOperator">
        <option value="0">Select category</option>
        <option th:each="categories : ${categories}" th:value="${categories.name}"
                th:text="${categories.name}"></option>
    </select>

    <button type="submit" > Save Wallet</button>
</form>

This is controller to save that form:

   @PostMapping("/saveTransaction/{walletId}")
   public String saveTransaction(@PathVariable(value = "walletId") long walletId, 
   @ModelAttribute("transaction") Transaction transaction) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
    long userId = user.getId();

    Wallet wallet = walletService.getWalletById(walletId);


    transaction.setWallet(wallet);
    transactionService.saveTransaction(transaction);
    return "redirect:/api/wallet/userWallet/balance/"   userId;
}

This is controller that show form:

    @GetMapping("/showNewTransactionForm/{id}")
public String showNewTransactionForm(@PathVariable(value = "id") long id, Transaction transaction, Model model) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
    long userId = user.getId();
    model.addAttribute("userId", userId);

    model.addAttribute("transaction", transaction);
    List<Category> categories = categoryService.getAllCategories();
    model.addAttribute("categories", categories);

    return "new_transaction";

}

This is category entity:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "category_id")
private Long id;

@Column(name = "category_name")
private String name;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private List<Transaction> transactions;

This is transaction entity:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "transaction_id")
private Long id;

private double amount;

private String note;

@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name = "date")
private Date date;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "category_name", referencedColumnName = "category_name")
private Category category;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="wallet_id", nullable=false)
private Wallet wallet;

Any advice what I can try? I had an error for that field that says Cannot add or update a child row a foreign key constraint fails but I fixed it somehow and now there is no errors at all, just field is not saved into database, but, as I said I can insert it manually successful in MySQL.

CodePudding user response:

Maybe you should try writing that, because th: field is equivalent to th:name th:value

<select  id="dropOperator">
    <option value="0">Select category</option>
    <option th:each="categories : ${categories}" th:value="${categories.id}"
            th:text="${categories.name}" th:name="*{category.name}"></option>
</select>
  • Related