1

我目前正在使用 scala (2.11)、Playframework (2.2.3) 和 MongoDB (with Salat) 编写我的第一个应用程序。由于我不太了解它们中的任何一个,所以我遇到了一个初学者问题:我无法从表单提交数据。

我不确定是否有人可以帮助我解决我的确切问题,但也许有人可以指出我正确的方向?

我目前的错误是:

[error] .../app/controllers/api/Users.scala:96: Cannot find Formatter type class for se.radley.plugin.salat.Binders.ObjectId. Perhaps you will need to import play.api.data.format.Formats._ 
[error]     "id" -> of[ObjectId],
[error]               ^
[error] .../app/views/user.scala.html:7: type mismatch;
[error]  found   : play.api.mvc.EssentialAction
[error]  required: String
[error]     @helper.form(action = new play.api.mvc.Call("POST",api.Users.create)) {

这是我的代码:查看 - users.scala.html

@(userForm: Form[User])
@import views.html.helper._
@main("create new user") {
     @helper.form(action = new play.api.mvc.Call("POST",api.Users.create)) {
        @helper.inputText(userForm("username"))
        <!-- other fields -->
        <button type="submit">Create</button>
    }
}

我的控制器的一部分 - Users.scala

 def create = JsonAction[SUser] { user =>
    SUser.save(user, WriteConcern.Safe)
    Ok(views.html.user(userForm)),

 def createForm() = Action {
   Ok(views.html.user(userForm))
 }

val userForm = Form(mapping(
  "id" -> of[ObjectId],
  "username" -> nonEmptyText,
  // other fields
)(SUser.apply)(SUser.unapply))

我对此请求的路线:

POST    /user               controllers.api.Users.create()

最后是我的模型 - User.scala

case class User(
    id: ObjectId = new ObjectId,
    username: String,
    // etc

object User extends UserDAO with UserJson

trait UserDAO extends ModelCompanion[User, ObjectId] {
  def collection = mongoCollection("users")
  val dao = new SalatDAO[User, ObjectId](collection) {} /* other methods */ }

trait UserJson {

implicit val userJsonWrite = new Writes[User] {
  def writes(u: User): JsValue = {
    Json.obj(
      "id" -> u.id,
      "username" -> u.username,
      /* etc */ )}} 

implicit val userJsonRead = (
  (__ \ 'id).read[ObjectId] ~
  (__ \ 'username).read[String] ~
  /* etc */ ) (User.apply _)

在 Play for Scala (Manning) 的帮助下,我基于https://github.com/leon/play-salat尝试了许多不同的变体,以及我在该主题上找到的谷歌链接。在我看来,这是一个非常明显的问题,但正如我所说,我对这些主题很陌生。如果有人能指出我正确的方向,甚至给我发教程或其他东西,那就太好了!谢谢!

4

0 回答 0