【问题标题】:NoSuchElementException: None.get in play framework for scalaNoSuchElementException: None.get in play framework for scala
【发布时间】:2015-01-30 18:29:07
【问题描述】:

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

用户控制器

   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

【问题讨论】:

  • Form 上使用.get 是不安全的。它抛出异常是因为存在验证错误,因此无法绑定到对象。
  • 我应该用什么?
  • 你应该使用 fold 而不是 .get formMapping.feeForm.bindFromRequest.fold( formWithErrors =&gt; { ??? }, dataOnSuccess =&gt; ??? ) }

标签: scala playframework crud slick


【解决方案1】:

Play page on Scala Forms 在这里很有帮助。该方法是将填充的表单作为参数发送到视图,然后在提交时使用fold,它为您提供了处理错误情况以及“快乐”情况的选项。类似于以下内容(改编自上述页面):

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 会不起作用吗?

【讨论】:

    【解决方案2】:

    你导入了吗

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多