1

我正在研究这个 Scala Play 应用程序,经过研究和思考后,我倾向于一种将所有表单放在表单包下的设计,在视图中使用它们的级别(或应用的最顶层),例如

 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每次创建一个新实例。

4

1 回答 1

1

使用guice依赖注入创建PasswordChangeForm一个单例类并注入。MessagesApi

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

用法:

messages("somekey")

上面的结构是单例的,由guice保证。Guice 在PasswordChangeForm.

于 2016-12-12T20:39:53.863 回答