gpt4 book ai didi

scala - 玩!从单独的 mongo 集合中选择项目的表单

转载 作者:可可西里 更新时间:2023-11-01 09:52:58 24 4
gpt4 key购买 nike

所以对于我正在开发的系统,我正在尝试做类似的事情:

如果我有一个名为 User 的模型,它有一个 _id (ObjectId)、用户名、密码,然后我尝试创建一个新约会,我的表单将查找患者(在下拉列表中显示患者姓名,但真的会拿起病人的 ObjectId)和预约时间。

现在我四处寻找,找不到任何与我试图获得的解决方案相差甚远的东西。

在 Application.scala 中,我有:

val appointmentForm= Form(
tuple(
"patient" -> nonEmptyText, // ObjectId
"startTime" -> nonEmptyText))

我不确定如何充分发挥我的观点以反射(reflect)患者的情况。我知道你必须做这样的事情:

@select(appointmentForm("patient"), options(..)

任何人都可以告诉我如何查找此示例的患者以获取 Mongo ObjectId。

顺便说一句,我使用的 ORM 是 https://github.com/leon/play-salat

最佳答案

这是我将如何做的一个例子:

路线:

GET      /test        controllers.Test.show
POST /test controllers.Test.submit

查看:

@(f: Form[(ObjectId, String)], users: Seq[(ObjectId, String)])
@import helper._

@form(action = routes.Test.submit) {
@select(f("patient"), options = users.map(user => (user._1.toString, user._2)))
@inputText(f("startTime"))
<input type="submit" value="Submit!">
}

Controller :

package controllers

import org.bson.types.ObjectId
import play.api.data.format.Formatter
import play.api.mvc._
import play.api.data.Forms._
import play.api.data._
import play.api.data.FormError
import play.api.Logger

object Test extends Controller {

/**
* Converts an ObjectId to a String and vice versa
*/
implicit object ObjectIdFormatter extends Formatter[ObjectId] {
def bind(key: String, data: Map[String, String]) = {
val error = FormError(key, "error.required.ObjectId", Nil)
val s = Seq(error)
val k = data.get(key)
k.toRight(s).right.flatMap {
case str: String if (str.length() > 0) => Right(new ObjectId(str))
case _ => Left(s)
}
}
def unbind(key: String, value: ObjectId) = Map(key -> value.toStringMongod())

val objectId: Mapping[ObjectId] = of[ObjectId]
}

// import to get objectId into scope
import ObjectIdFormatter._

// define user tuples consisting of username and ObjectId for the dropdown. In real lif the list is probably fetched from the db
def users: Seq[(ObjectId, String)] =
Seq((new ObjectId("4f456bf744aed129d04db1bd"), "dieter"), (new ObjectId("4faa410b44aec5a0a980599f"), "eva"))

val appointmentForm= Form(
tuple(
"patient" -> objectId, // use the ObjectIdFormatter
"startTime" -> nonEmptyText))


def show = Action {
Ok(views.html.test(appointmentForm, users))
}

def submit = Action { implicit request =>
appointmentForm.bindFromRequest.fold(
formWithErrors => {
Logger.warn("errors: " + formWithErrors.errors)
BadRequest(views.html.test(formWithErrors, users))
},
formContent => {
Logger.info("formContent: " + formContent)
Ok(views.html.test(appointmentForm, users))
})
}
}

关于scala - 玩!从单独的 mongo 集合中选择项目的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11890379/

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