Play 2.0 用户指南 - 表单提交和验证 --针对Scala开发者

处理表单提交

     定义一个表单

    play.api.data 包中包含了一些助手方法,用于处理HTTP表单数据提交和验证。操纵表单提交最容易的方式是定义一个 play.api.data.Form 结构:

1import play.api.data._ 2import play.api.data.Forms._ 3 4val loginForm = Form( 5 tuple( 6 "email" -> text, 7 "password" -> text 8 ) 9)

    该表单可以从Map[String,String]中生成一个(String, String)结果值。

1val anyData = Map("email" -> "bob@gmail.com", "password" -> "secret") 2val (user, password) = loginForm.bind(anyData).get

    如果在上下文中包含request,你还可以直接从request内容中绑定:

val (user, password) = loginForm.bindFromRequest.get

    构造复杂对象

    一个表单对像可以使用函数来构造和解构值。例如你可以定义一个form来包装已有的case class:

1import play.api.data._ 2import play.api.data.Forms._ 3 4case class User(name: String, age: Int) 5 6val userForm = Form( 7 mapping( 8 "name" -> text, 9 "age" -> number 10 )(User.apply)(User.unapply) 11) 12 13val anyData = Map("email" -> "bob@gmail.com", "age" -> "18") 14val user: User = userForm.bind(anyData).get

    注意:使用 tuple 和 mapping 的不同在于,当你使用 tuple 时,构造和析构不需要指定(我们知道怎样构造和解构一个tuple,对吧?)。
         mapping 方法仅让你定义你的自定义函数。当你想构造和解构一个case class,你只不过是使用 apply 和 unapply 函数,它们能精确的做到。

    当然,通常Form签名不会精确的匹配case class。让我们举个包含额外的 checkbox 字段标识是否接受服务条款的例子。我们不需要將checkbox属性加入User类中。
    它只是为了表单验证而加入的一个虚拟字段,一旦验证通过,该值便毫无用处。
    
    由于我们可以自定义构造和解构函数,很容量处理这种情形:

1val userForm = Form( 2 mapping( 3 "name" -> text, 4 "age" -> number, 5 "accept" -> checked("Please accept the terms and conditions") 6 )( 7 (name, age, _) => User(name, age), 8 (user: User) => Some(user.name, user.age, false) 9 ) 10)

    注意:解析函数用于我们使用现有的User值填充表单的时候。这会对当我们需要从数据库加载User对象,填充表单,修改的这类用例很帮助。

    定义约束

    每一次映射,你都可以定义额外的约束,它將在绑定阶段被检查:
  

1import play.api.data._ 2import play.api.data.Forms._ 3import play.api.data.validation.Constraints._ 4 5case class User(name: String, age: Int) 6 7val userForm = Form( 8 mapping( 9 "name" -> text verifying(required), 10 "age" -> number verifying(min(0), max(100)) 11 )(User.apply)(User.unapply) 12)

    注意:也可以写成

1mapping( 2 "name" -> nonEmptyText, 3 "age" -> number(min=0, max=100) 4)

你也可以在字段上特设一些限制:

1val loginForm = Form( 2 tuple( 3 "email" -> nonEmptyText, 4 "password" -> text 5 ) verifying("Invalid user name or password", { 6 case (e, p) => User.authenticate(e,p).isDefined 7 }) 8)

    处理绑定失败

    如果你定义了约束,你也需要处理绑定失败的情形。你可以使用 fold 完成:

1loginForm.bindFromRequest.fold( 2 formWithErrors => // binding failure, you retrieve the form containing errors, 3 value => // binding success, you get the actual value 4)

    使用默认初始值填充表单

    有时,你需要用现有值填充表单,特别是编辑数据的时候:

val filledForm = userForm.fill(User("Bob", 18))

    嵌套值

    表单映射可以定义嵌套值:

1case class User(name: String, address: Address) 2case class Address(street: String, city: String) 3 4val userForm = Form( 5 mapping( 6 "name" -> text, 7 "address" -> mapping( 8 "street" -> text, 9 "city" -> text 10 )(Address.apply)(Address.unapply) 11 )(User.apply, User.unapply) 12)

    当你使用这种嵌套值的时候,从浏览器发送来的表单数据必须像address.street , address.city这样命名。

    列表值

    表单映射可以定义列表值:

1case class User(name: String, emails: List[String]) 2 3val userForm = Form( 4 mapping( 5 "name" -> text, 6 "emails" -> list(text) 7 )(User.apply, User.unapply) 8)

    当你像这样使用列表值时,从浏览器发来的表单数据必须使用类似emails[0] , emails[1] , emails[2]的方式命名。
    

    可选值

    表单映射也可以定义可选值:

1case class User(name: String, email: Option[String]) 2 3val userForm = Form( 4 mapping( 5 "name" -> text, 6 "email" -> optional(text) 7 )(User.apply, User.unapply) 8)

    注意:如果request不包含该值或值为空时,email域將会被忽略并设为None。

    现在你可以综合可选值,嵌套和列表值来处理任何复杂的表单。

    使用表单模版助手

    Play提供了几个在HTML模版中渲染表单字段的助手方法。

    创建<form>标签

    第一件事是能够创建<form>标签。它是一个简单的助手方法,毋需更多的值就会自动根据值入的反向路由自动设置action和method。

1@helper.form(action = routes.Application.submit) { 2 3}

    你也可以传递一些额外的HTML表单属性值:

1@helper.form(action = routes.Application.submit, 'id -> "myForm") { 2 3}

    渲染<input>元素

    
    在views.html.helper包中,你会发现几个input助手。向form提供字段,它们会相应设置input值,包括约束和错误:

1@(myForm: Form[User]) 2 3@helper.form(action = routes.Application.submit) { 4 5 @helper.inputText(myForm("username")) 6 7 @helper.inputPassword(myForm("password")) 8 9}

    你也可以指定额外的Html属性:

@helper.inputText(myForm("username"), 'id -> "username", 'size -> 30)

    注意:所有的额外元素都將加入生成的Html中,除非它们以_开头。以 _ 开头的参数保留给字段构造做为参数(稍后我们將会看到)。

     自定义HTML input 创建

    这是一个更加通用的 input 助手方法,让你编写所需的HTML结果:
    

1@helper.input(myForm("username")) { (id, name, value, args) => 2 <input type="date" name="@name" id="@id" @toHtmlArgs(args)> 3}

    字段构造器

    一个字段不光由 input 标签组成,它也可能也需要 由<label> 和其它被你的CSS框架所需的标签装饰而成。
    所有的input助手都拥有一个隐式的FieldConstructor处理该部分。默认生成的Html代码看起来像这样:

1<dl class="error" id="username_field"> 2 <dt><label for="username"><label>Username:</label></dt> 3 <dd><input type="text" name="username" id="username" value=""></dd> 4 <dd class="error">This field is required!</dd> 5 <dd class="error">Another error</dd> 6 <dd class="info">Required</dd> 7 <dd class="info">Another constraint</dd> 8</dl>

    默认字段构造器支持几个额外的可选值,你可以通过参数传递给input函数:

1'_label -> "Custom label" 2'_id -> "idForTheTopDlElement" 3'_help -> "Custom help" 4'_showConstraints -> false 5'_error -> "Force an error" 6'_showErrors -> false

    Twitter bootstrap 字段构造器

    
    我们提供了另外一个内建的字段构造器可以配合TwitterBootstrap一起使用。
    
    要使用它,仅需在当前上下文中导入:

@import helper.twitterBootstrap._

    它生成的Html看起来像这样:

1<div class="clearfix error" id="username_field"> 2 <label for="username">Username:</label> 3 <div class="input"> 4 <input type="text" name="username" id="username" value=""> 5 <span class="help-inline">This field is required!, Another error</span> 6 <span class="help-block">Required, Another constraint</d</span> 7 </div> 8</div>

    它提供和默认字段构造器同样的功能集(参照之前描述)。

    编写自定义字段构造器

    通常你都需要编写自定义字段构造器。可通过以下模版起步:

1@(elements: helper.FieldElements) 2 3<div class="@if(elements.hasErrors) {error}"> 4 <label for="@elements.id">@elements.label</label> 5 <div class="input"> 6 @elements.input 7 <span class="errors">@elements.errors.mkString(", ")</span> 8 <span class="help">@elements.infos.mkString(", ")</span> 9 </div> 10</div>

   注意:这仅仅是个例子。你可以按需改造他。你也可以通过 @elements.field 访问字段原型。

    现在,使用模版函数创建一个FieldConstructor。

1object MyHelpers { 2 3 implicit val myFields = FieldConstructor(myFieldConstructorTemplate.f) 4 5}

    为了让form方法使用它,仅需將它导入你的模版中:

1@import MyHelpers._ 2 3@inputText(myForm("username"))

    它將使用field constructor来渲染输入值。
    注意:你也可以在模版中为FieldConstructor内嵌一个隐式值:

1@implicitField = @{ FieldConstructor(myFieldConstructorTemplate.f) } 2 3@inputText(myForm("username"))

    处理列表值

    最后的一个助手方法能让你轻松的创建列表输入值。假定你有一个如下的表单定义:

1val myForm = Form( 2 tuple( 3 "name" -> text, 4 "emails" -> list(email) 5 ) 6)

    现在你需要为emails字段生成很多列表值包含在form中。使用列表值助手完成:

1@inputText(myForm("name")) 2 3@repeat(myForm("emails"), min = 1) { emailField => 4 5 @inputText(emailField) 6 7}

    The min parameter allows you to display a minimum number of fields even if the corresponding
    form data are empty.

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

java将前端的json数组字符串转换为列表

记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang