0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

htmxを使ってみた-(7)データ追加-

Last updated at Posted at 2024-10-22

データの追加ダイアローグを出す

練習プログラムでは、一覧表の最下部に、追加ボタンを取り付けています。
04.png
ボタンのHTMLデータは、htlm00.jsのテンプレート内で次のように作っています。

<input type="button" value="施設追加" hx-get="/new_institution" hx-target="#detail" hx-on::after-request="show_dialog()">

「施設追加」ボタンを押すと、次のようなダイアローグが出てきます。
05.png
ダイアローグの内容はhtml04.j2です。
「個別表示」と同じようにして、<dialog>の中身を変えています。

AJAXリクエストのトリガー

htmxは標準で次のようなイベントが起きたときに、AJAX通信を行います。

HTMLタグ トリガー
input、textarea、select 内容が変わったとき(onChange)
form submitされたとき(submitボタンが押された)(onSubmit)
その他 クリックされたとき(onClick)

とても”自然”なAJAXリクエストとなっています。
標準を変えたい場合は、hx-trigger属性で指定します。
hx-trigger では、コントロールキーを押しながら等の修飾も加えることができます。

データ追加ダイアローグ

html04.j2がダイアローグの中身です。

<form hx-post="/add_institution" hx-target="#add_btn" hx-swap="beforebegin">
	<input type="hidden" name="ID" value="-1">
	<table style="width:27rem">
		<tr>
			<th>名称</th>
			<td><input type="text" required name="name" value=""></td>
		</tr>
  <!-- 中略 -->
	</table>
	<div class="right_button">
		<input type="submit" value=" 追加 ">
		<input type="button" value="閉じる" onclick="close_dialog()" autofocus>
	</div>
</form>

練習プログラムでは、

  1. 「追加」(type=submit)ボタンが押されると、submitイベントが発火し、
  2. hx-post属性により、HTTPのPOSTメソッドで、サーバーの/add_institutionにアクセスし、
  3. hx-target属性により、サーバーからの応答で、idにadd_btn"を持つタグの中身を、
  4. hx-swap属性による方法(beforebegin)に従って書き換えます。

hx-swap属性ではbeforebeginが指定されていますので、hx-target属性で指定される要素の前に、応答が追加されます。
サーバー側のプログラムは、p04.pyにある、add_institution()関数です。
add_institution()関数は送られてきたデータをデータベースに登録し、成功した場合は、登録データを整形成形して返します。
登録に失敗した場合は、エラーを返します。

htmxによってformタグの動作が書き換えられている。

関連記事一覧

htmxを使ってみた-(1)htmxの基本-
htmxを使ってみた-(2)準備-
htmxを使ってみた-(3)ルート関数-
htmxを使ってみた-(4)htmxを使う-
htmxを使ってみた-(5)HTMLのdialog-
htmxを使ってみた-(6)データの表示-
htmxを使ってみた-(7)データ追加-
htmxを使ってみた-(8)要素の変更-
htmxを使ってみた-(9)ページの再読み込み-
htmxを使ってみた-(10)データの変更-
htmxを使ってみた-(11)データベースの排他制御-
htmxを使ってみた-(12)確認ダイアローグ-
htmxを使ってみた-(13)データ削除-(最終)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?