scalaplayframeworkplayframework-2.3

How to map checkboxes in Play Framework with Scala Forms?


I have a project on Play Framework 2.3 with Scala.

I have a model:

case class User(
      name: String,
      login: String,
      password: String,
      isAdministrator: Boolean)

And form in views without play form helpers:

<form action="@controllers.routes.Users.create()" method="POST">
    <input type="text" name="login">
    <input type="text" name="name">
    <input type="password" name="password">
    <input type="checkbox" name="isAdministrator">
    <button type="submit" class="btn btn-success">Save</button>
</form>

Try to map it in controllers, with scala forms:

val userForm = EntityForm[User](
  _.name -> nonEmptyText,
  _.login -> nonEmptyText,
  _.password -> nonEmptyText,
  _.isAdministrator -> boolean,
  _.serviceProviderId -> optional(number)
)

def create = Action { implicit request =>
  userForm.bindFromRequest.fold(
    formWithErrors => BadRequest(
      views.html.users.userNew()
    ),
    user => { 
      //saving user code
    }
  )
}

And that always works like it'is bad request. Debugger shows me, that an error in checkbox mapping. The checkbox in request looks like: password -> ArrayBuffer(on)

Also I try same with:

_.isAdministrator -> checked("on"),

And it doesn't works too. What are the right way to map checkbox in Play Framework with Scala Forms?


Solution

  • All following code works, when you add value="true" to checkbox, like this:

    <input type="checkbox" name="isAdministrator" value="true"/>