Swift Vapor Form(method:post)による送信と結果表示
Vapor Formによる送信と結果表示をまとめる。
APIドキュメント:https://api.vapor.codes/vapor/documentation/vapor
入力画面(Form)
Resources/Views/exampleform.leaf
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>例:Form</title>
</head>
<body>
<form action="./exampleformaction" method="post">
<label for="name">名前</label>
<input type="text" id="name" name="name"><br />
<label for="name">年齢</label>
<input type="number" id="age" name="age"><br />
<input type="submit" value="送信する">
</form>
</body>
</html>
結果画面
Resources/Views/exampleformresult.leaf
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>例:Form結果</title> </head> <body> <p>お名前:#(name)</p> <p>年齢:#(age)</p> </body> </html>
Form送信データ取得・変換用モデル
Sources/App/Models/ExampleForm.swift
Contentプロトコルに準拠させる。
API Document:Content
Content
Convertible to / from content in an HTTP message.
import Vapor
final class ExampleForm: Content {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
Form画面と結果画面を返す
Sources/App/routes.swift
今回はControllerは作成せず、routesに直書きで対応。
post側の「req.content.decode」で、Form送信データからモデルに変換している。
import Fluent
import Vapor
func routes(_ app: Application) throws {
app.get("exampleform") { req async throws in
try await req.view.render("exampleform")
}
app.post("exampleformaction") { req async throws -> View in
let exampleForm = try! req.content.decode(ExampleForm.self)
print("name:\(exampleForm.name)")
print("age:\(exampleForm.age)")
return try await req.view.render("exampleformresult", exampleForm)
}
}








