2016-12-12 10 views
1

私はthis Scala Play applicationに取り組んでいます。すべてのフォームをフォームパッケージの下に置いて、ビュー(または適用される最上位レベル)問題は、私はエラー報告用フォームへMessages以上MessagesApiを使用可能にする方法を見ていないですScala Play 2.5フォームの規約と暗黙のメッセージ(MessagesApi)へのアクセス

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)) 
    } 
} 

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

その後PasswordChangeForm.scala形式は、次のように実装されています。

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"), 

UPDATE可能性から上記溶液をリファクタリングすることである。

def create(implicit messages: Messages) = Form { 

val Instance = Form { 

しかし、それthの新しいインスタンスを作成しますe Form毎回。

答えて

1

PasswordChangeFormをシングルトンクラスにし、MessagesApiをguice依存性注入を使用してください。

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

使用:

messages("somekey") 

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

+1

ありがとうございます!私は 'messages:Messages'を少し流行りしているのを除いて、同じ解決策に収束しました:) –

関連する問題