Scala Play 2.5表单约定和隐式消息(MessagesApi)访问

时间:2016-12-12 19:36:34

标签: scala playframework play-authenticate

我正在研究this Scala Play application并且在研究和思考之后有点结束了一种设计,它将所有表单放在一个表单包下面,在它们在视图中使用的级别(或最顶层)适用)例如

 app
    | views 
           | account
                    | form (all Form used by account will be here)
                          | PasswordChangeForm.scala

然后PasswordChangeForm.scala表单实现为:

package views.account.form

import play.api.data.Form
import play.api.data.Forms.{mapping, text}
import play.api.i18n.Messages

case class PasswordChange(password: String, repeatPassword: String)

object PasswordChangeForm {
  val Instance = Form {
    mapping(
      "password" -> text(minLength = 5),
      "repeatPassword" -> text(minLength = 5)
    )(PasswordChange.apply)(PasswordChange.unapply).
      verifying(Messages("playauthenticate.change_password.error.passwords_not_same"),
        data => data.password != null && !data.password.isEmpty && data.password.equals(data.repeatPassword))
  }
}

问题是我不知道如何使Messages或更好MessagesApi可用于错误报告的表单。

编译器错误符合预期could not find implicit value for parameter messages: play.api.i18n.Messages

[error] /home/bravegag/code/play-authenticate-usage-scala/app/views/account/form/PasswordChangeForm.scala:15: could not find implicit value for parameter messages: play.api.i18n.Messages
[error]       verifying(Messages("playauthenticate.change_password.error.passwords_not_same"),

更新有可能重构以上解决方案:

val Instance = Form { 

def create(implicit messages: Messages) = Form {

但是每次都会创建Form的新实例。

1 个答案:

答案 0 :(得分:1)

使用guice依赖注入使Sub IDgen() Dim ID, Yr, Dt, Mth, Hr, Min As Integer ID = Environ("username") Yr = Right(Year(Date), 2) Mth = Format(Month(Date), "#00") Dt = Format(Day(Date), "#00") Hr = Format(Hour(Time), "#00") Min = Format(Minute(Time), "#00") Sheets("Sheet1").Range("A2").Value = "C" & Yr & Mth & Dt & "." & Hr & Min & "." & ID End Sub 成为单例类并注入PasswordChangeForm

MessagesApi

用法:

@Singleton
class PasswordChangeForm @Inject() (messages: MessagesApi) {
  //now use it like this messages("somekey")
}

上述结构是单身,由guice确保。 Guice在messages("somekey") 初始化期间注入消息api。