simonC
simonC

Reputation: 4327

implicit messages compile error in play2.5

I have a play2.5 app and a form where i would like to have the error messages internationalized. I have the form in a separate object and use it in the controller. But play dos not compile because could not find implicit messages.

I suppose this is a trivial solution but I'm new to play and scala, and would be grateful for any hint.

Error:(14, 45) could not find implicit value for parameter messages: play.api.i18n.Messages "username" -> email.verifying(Messages("error.email.required"), {!_.isEmpty}),

object LoginForm {

  val form = Form(
    mapping(
      "username" -> email.verifying(Messages("error.email.required"), {!_.isEmpty}),
      "pasword" -> nonEmptyText(8,20).verifying(Messages("error.password.required"), {!_.isEmpty})
    )(Data.apply)(Data.unapply)
  )

  case class Data(
    username: String,
    password: String
  )

}

Upvotes: 0

Views: 72

Answers (2)

josephpconley
josephpconley

Reputation: 1723

You need to use the I18nSupport trait to get the implicit play.api.i18n.Messages value in scope. Full explanation here:

https://www.playframework.com/documentation/2.5.x/ScalaI18N#Externalizing-messages

For your use-case, the simplest approach would be to define the form inside of a controller which uses the I18nSupport trait. As you're new to Scala and Play I'd recommend this approach.

A more advanced approach would be to define the form in a LoginForm trait and declare a dependency on the I18nSupport trait. This would look like:

trait LoginForm{
  self: I18nSupport =>

  //define form here
}

Then you would just mixin this LoginForm trait to the controller you need it in (which should be mixing in the I18nSupport trait).

Upvotes: 1

tgk
tgk

Reputation: 4096

Does it work if you implicitly provide lang to the form like this?

def form(implicit lang: Lang) = Form(
    mapping(
      "username" -> email.verifying(Messages("error.email.required"), {!_.isEmpty}),
      "pasword" -> nonEmptyText(8,20).verifying(Messages("error.password.required"), {!_.isEmpty})
    )(Data.apply)(Data.unapply)
  )

It can sometimes be nice to move the form to the companion object of the case class:

case class Data(
    username: String,
    password: String
  )

object Data {
  def form(implicit lang: Lang) = ...
}

Upvotes: 0

Related Questions