播放框架如何重用和扩展表单映射

时间:2014-06-30 15:54:03

标签: scala playframework-2.0

我有一个表单映射,如下所示:

val myBaseMapping =  mapping(
  "email"                -> email,
  "password"             -> text.verifying("Please provide a password", !_.isEmpty)
)(BaseModel.apply)(BaseModel.unapply)

这代表FormA。我有另一种形式FormB,它是相同的,但增加了几个字段。这就是它的映射看起来像:

val myExtendedMapping =  mapping(
  "email"                -> email,
  "password"             -> text.verifying("Please provide a password", !_.isEmpty)
  "name"                 -> text,
  "website"              -> text
)(ChildModel.apply)(ChildModel.unapply)

ChildModel扩展了BaseModel:它添加了2个新字段,namewebsite

我正在尝试以这样的方式对myExtendedMapping进行编码,以至于我不必复制共享字段(电子邮件和密码)的绑定定义。

我不确定Scala的语法是什么。我不知道如何扩展'给定的映射并添加绑定。此外,由于行为的不同,我不想添加临时验证。这是可能的还是我只需重复代码?

1 个答案:

答案 0 :(得分:0)

你能做的就是一个简单的作品。例如:

case class BaseModel(email: String, password: String)
case class ChildModel(name: String, website: String, base: BaseModel)

val commonMapping = mapping(
  "email" -> email,
  "passwod" -> texttext.verifying("Please provide a password", !_.isEmpty)
)(BaseModel.apply)(BaseModel.unapply)

val myExtendedForm = Form[ChildModel](mapping(
   "name" -> text,
   "website" -> text,
   "base" -> commonMapping
)
   ((name, website, base) => ChildModel(name, website, base))  //bind
   (child => Some(child.name, child.website, child.base))      //unbind
)