email, "password" -6ren">
gpt4 book ai didi

scala - 玩框架如何重用和扩展表单映射

转载 作者:行者123 更新时间:2023-12-02 04:54:18 26 4
gpt4 key购买 nike

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

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

我正在尝试以不必为共享字段(电子邮件和密码)复制绑定(bind)定义的方式编写 myExtendedMapping 代码。

我不确定这里的 Scala 语法是什么。我不知道如何“扩展”给定的映射并向其添加绑定(bind)。另外,由于行为上的差异,我不想添加临时验证。这是可能的还是我只需要复制代码?

最佳答案

你能做的就是一个简单的构图。例如:

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
)

关于scala - 玩框架如何重用和扩展表单映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24494190/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com