LoginSignup
0
0

More than 1 year has passed since last update.

Thymeleaf 行単位でデータをpost送信する

Last updated at Posted at 2021-09-29

削除ボタンを押下してID情報を取得する例

image.png

同じ<td>内にhiddenとsubmitタイプの<input>を設置する

<td>
 <form method="post" th:action="@{/shopping_list}">
   <input type="hidden" name="id" th:value="*{id}">
   <input type="submit" value="削除">
 </form>
</td>  

image.png

ビュー側

<table border="5" frame="box" cellpadding="15">
  <tr>
    <th>ID</th>
    <th>商品</th>
    <th>備考</th>
    <th></th>
  </tr>

  <tr th:each="shoppingList:${List}" th:object="${shoppingList}">
    <td th:text="*{id}"></td>
    <td th:text="*{itemName}"></td>
    <td th:text="*{remark}"></td>
    <td>
      <form method="post" th:action="@{/shopping_list}">
        <input type="hidden"  name="id" th:value="*{id}">
        <input type="submit" value="削除">
      </form>
    </td>  
  </tr>
</table>

ポイント 解説 備考
input type="hidden" ブラウザ上は表示されないが、コントローラーに値を渡せる。
https://developer.mozilla.org/ja/docs/Web/HTML/Element/input
name="id" th:value="*{id}" nameで指定した値とEntityクラスの変数名が紐づいているので、nameを省略したり、th:name="*{id}" 、name="aaa"等してしまうと意図した動作をしない。
input type="submit" コントローラーにフォームの値を渡す

コントローラー側

@RequestMapping("/shopping_list")
public String getShoppingList(Model model,ShoppingListForm shoppingListForm,Integer id){

  //リストの削除
  shoppingListService.deleteShoppingList(shoppingListForm);         
  //買い物リストの生成
  List<ShoppingList> List = shoppingListService.findAll();
  model.addAttribute("List",List);       

  return "shopping_list";
}
ポイント 解説 備考
Integer id javaのEntityクラスで定義したフィールド変数と同じ型で定義にしないと、
型を解決出来ないためエラーになる。
ちなみにこの例ではjavaのformクラスにてidをInteger型で定義しているので、ここにintやlongで初期化するとエラーになる。

参考

HTML Thymeleaf

SpringBoot

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0