迁移至2.6和Form错误没有为play.i18n.Messages绑定任何实现

时间:2019-05-07 20:57:38

标签: scala playframework playframework-2.6

在我的项目中,我在控制器的范围之外定义了SignupForm……原因是我需要从其他源文件中重用它。

package views.form

import javax.inject.{Inject, Singleton}
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.Messages

case class Signup(email: String, password: String, repeatPassword: String, name: String) extends MyUsernamePassword

@Singleton
class SignupForm @Inject() (implicit val messages: Messages) {
  val Instance = Form {
    mapping(
      "email" -> email,
      "password" -> nonEmptyText(minLength = 5),
      "repeatPassword" -> nonEmptyText(minLength = 5),
      "name" -> nonEmptyText
    )(Signup.apply)(Signup.unapply).
      verifying(messages("playauthenticate.password.signup.error.passwords_not_same"),
        data => (data.password != null) && data.password.equals(data.repeatPassword))
  }
}

但这会导致运行时错误No implementation for play.i18n.Messages was bound。我该如何解决?

1 个答案:

答案 0 :(得分:2)

迁移到MessagesApi

import javax.inject.{Inject, Singleton}
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.{Lang, Langs, MessagesApi}

case class Signup(email: String, password: String, repeatPassword: String, name: String) extends MyUsernamePassword

@Singleton
class SignupForm @Inject() (implicit val langs: Langs, val messagesApi: MessagesApi) {
  implicit val lang: Lang = langs.availables.head
  val Instance = Form {
    mapping(
      "email" -> email,
      "password" -> nonEmptyText(minLength = 5),
      "repeatPassword" -> nonEmptyText(minLength = 5),
      "name" -> nonEmptyText
    )(Signup.apply)(Signup.unapply).
    verifying(messagesApi("playauthenticate.password.signup.error.passwords_not_same")(lang),
      data => (data.password != null) && data.password.equals(data.repeatPassword))
  }
}

您需要在配置文件中指定语言。例如,play.i18n.langs = [ "en", "en-US", "fr" ]。可以在here中找到更多详细信息。