我上周刚刚发现了Scala语言,Play 2 Framework,我有点困惑......
我尝试使用本教程制作一个包含用户名和密码的简单表单:
但是在控制器中我有一个不起作用的功能:
def addUser() = Action { implicit request =>
userForm.bindFromRequest.fold(
errors => BadRequest,
{
case (username) =>
User.create(User(NotAssigned, username, password))
Redirect(routes.Application.index())
}
)
}
返回:未找到:值密码
如果我把密码放在案件中,它也不会发出警告......
有什么想法吗?
Application.scala:
package controllers
import play.api._
import play.api.mvc._
import play.api.data.Form
import play.api.data.Forms.{single, nonEmptyText}
import play.api.mvc.{Action, Controller}
import anorm.NotAssigned
import models.User
object Application extends Controller {
val userForm = Form {
tuple(
"username" -> nonEmptyText,
"password" -> nonEmptyText
)
}
def index = Action {
Ok(views.html.index(userForm))
}
def addUser() = Action { implicit request =>
userForm.bindFromRequest.fold(
errors => BadRequest,
{
case (username, password) =>
User.create(User(NotAssigned, username, password))
Redirect(routes.Application.index())
}
)
}
}
User.scala:
package models
import play.api.db._
import play.api.Play.current
import anorm._
import anorm.SqlParser._
case class User(id: Pk[Long], username: String, password: String)
object User {
val simple = {
get[Pk[Long]]("id") ~
get[String]("username") ~
get[String]("password") map {
case username~password => User(id, username)
case id~username => User(id, username)
}
}
def findAll(): Seq[User] = {
DB.withConnection { implicit connection =>
SQL("SELECT * FROM user").as(User.simple *)
}
}
def create(user: User): Unit = {
DB.withConnection { implicit connection =>
SQL("INSERT INTO user(username, password) VALUES ({username}, {password})").on(
'username -> user.username ,
'password -> user.password
).executeUpdate()
}
}
}
答案 0 :(得分:2)
您要绑定的表单应包含您要提取的所有值,即:
import play.api.data.Form
import play.api.data.Forms.{tuple,nonEmptyText}
val userForm = Form(
tuple(
"username" -> nonEmptyText,
"password" -> nonEmptyText
)
)
def addUser() = Action { implicit request =>
userForm.bindFromRequest.fold(
errors => BadRequest,
{
case (username, password) => {
User.create(User(NotAssigned, username, password))
Redirect(routes.Application.index())
}
}
)
}
在James的示例中,表单只包含一个字段,该字段将提取为单个值(在您的情况下为用户名。)使用“元组”表单映射将允许您获取更多值。
答案 1 :(得分:0)
fold()函数的第二个参数是另一个函数,它接受您尝试绑定的Form类的对象。在你的情况下,它将是一个“userForm”对象:
def addUser() = Action { implicit request =>
userForm.bindFromRequest.fold(
errors => BadRequest,
okForm => {
// whatever you want
}
)
}
我们不知道您的表单类型。很难说更多。但是,至于我,在这里使用“案例”并不是一个好主意。