Swift Vapor Form(method:get)による送信と結果表示
Vapor Formによる送信と結果表示をまとめる。
APIドキュメント:https://api.vapor.codes/vapor/documentation/vapor
入力画面(Form)
Resources/Views/exampleformget.leaf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <! doctype html> < html lang = "en" > < head > < meta charset = "utf-8" > < title >例:Form</ title > </ head > < body > < form action = "./exampleformgetaction" method = "get" > < 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
1 2 3 4 5 6 7 8 9 10 11 12 | <! doctype html> < html lang = "en" > < head > < meta charset = "utf-8" > < title >例:Form結果</ title > </ head > < body > < p >お名前:#(name)</ p > < p >年齢:#(age)</ p > </ body > </ html > |
Form送信データ(URLパラメータ)取得・変換用モデル
Sources/App/Models/ExampleForm.swift
Contentプロトコルに準拠させる。
API Document:Content
Content
Convertible to / from content in an HTTP message.
1 2 3 4 5 6 7 8 9 10 11 | 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.query.decode」で、Form送信データ(URLパラメータ)からモデルに変換している。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import Fluent import Vapor func routes ( _ app : Application ) throws { app . get ( "exampleformget" ) { req async throws in return try await req . view . render ( "exampleformget" ) } app . get ( "exampleformgetaction" ) { req async throws - > View in print ( req . url ) let exampleForm = try ! req . query . decode ( ExampleForm . self ) print ( "name:\( exampleForm . name )" ) print ( "age:\( exampleForm . age )" ) return try await req . view . render ( "exampleformresult" , exampleForm ) } } |