我有一个表单映射,如下所示:
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个新字段,name
和website
。
我正在尝试以这样的方式对myExtendedMapping
进行编码,以至于我不必复制共享字段(电子邮件和密码)的绑定定义。
我不确定Scala的语法是什么。我不知道如何扩展'给定的映射并添加绑定。此外,由于行为的不同,我不想添加临时验证。这是可能的还是我只需重复代码?
答案 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
)