NoSuchElementException:在scala的play框架中的None.get

时间:2015-01-30 18:29:08

标签: scala playframework crud slick

我需要构建更新方法,但是当我测试时显示错误NoSuchElementException:None.get

UserController中

   object UserController extends Controller {

   def update(id:Long) = DBAction {  implicit rs =>

   var user = simpleUserForm.bindFromRequest.get

   user.id = Users.toOption(id)
   Users.update(user)
   Redirect(routes.UserController.list)
   }

   val simpleUserForm :Form[User] = Form {
     mapping(
       "firstName" -> nonEmptyText,
       "lastName" -> nonEmptyText,
       "email" -> email,
       "birthDate" -> nonEmptyText,
       "phone" -> nonEmptyText,
       "username" -> text,
       "password" -> nonEmptyText
     )(UserForm.fromSimpleForm)(UserForm.toSimpleForm)
   }

 }

edit.scala.html

@import models.auth.Users
@(title: String, user:models.auth.User)

@main(title){

<form method="post" action="@controllers.auth.routes.UserController.update(Users.toLong(user.id))">
    <input type="text" placeholder="First Name" name="firstName" value="@user.firstName"/><br/>
    <input type="text" placeholder="Last Name" name="lastName" value="@user.lastName"/><br/>
    <input type="email" placeholder="Email" name="email" value="@user.email" /><br/>
    <input type="text" placeholder="Phone" name="phone" value="@user.phone" /><br/>
    <input type="text" placeholder="Birthdate(dd/MM/yyyy)" name="birthDate" value="@user.birthDate" /><br/>
    <input type="text" placeholder="Username" name="username" value="@user.username" /><br/>

    <input type="submit" value="Update User" />
</form>
}

路线

POST        /user/:id/         controllers.auth.UserController.update(id:Long)

我已经完成了创建,读取和删除,但是对于更新我发现行中的错误     var user = simpleUserForm.bindFromRequest.get

错误是NoSuchElementException:None.get

2 个答案:

答案 0 :(得分:2)

Play page on Scala Forms在这里很有帮助。这种方法是将填充的表单作为参数发送到视图,然后提交使用fold,这将为您提供处理错误情况的选项以及&#34; happy&#34;案件。类似下面的内容(改编自上页):

simpleUserForm.bindFromRequest.fold(
  formWithErrors => {
    // binding failure, you retrieve the form containing errors:
    // in your form, test .hasErrors
    BadRequest(views.html.user.edit(formWithErrors))
  },
  userData => {
    /* binding success, you get the value. */
    // .. do the update
    ...
    //-- and return to list or home or...
    Redirect(routes.Application.home(id))
  }
)

如果您不想使用该表单,那么回到您的实际问题,.getOrElse会无效吗?

答案 1 :(得分:0)

你导入了吗

import play.api.libs.concurrent.Execution.Implicits._