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

PasswordChangeFormシングルトン クラスを作成し、 guiceMessagesApi依存性注入を使用して注入します。

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

利用方法:

messages("somekey")

上記の構造はシングルトンであり、Guice によって保証されます。Guice は の初期化中にメッセージ API を挿入しますPasswordChangeForm

于 2016-12-12T20:39:53.863 に答える