Reputation: 395
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?
Upvotes: 1
Views: 2292
Reputation: 1331
I know this is old question, but I've found it today looking for solution. Here is my way to map checkbox value, but I do not use case classes for mapping.
val isAdministrator = request.body.dataParts.get("isAdministrator").exists(_.nonEmpty)
I use this solution with Playframework 2.5.8
Upvotes: 1
Reputation: 395
All following code works, when you add value="true" to checkbox, like this:
<input type="checkbox" name="isAdministrator" value="true"/>
Upvotes: 1
Reputation: 1
This is more of a suggestion but I cannot comment since have less than 50 rep.
I think using JS calls to the server is less confusing for handling user input with Play, unless you want your site to work without JS.
Here's an example. I'm assuming you have a (POST) route set up for /doStuff/:parameter
HTML:
<textarea id="input"></textarea>
<button id="save">Save</button>
JS:
$("#save").click(function(){
var input = $("#input").val()
$.post("/doStuff/" + input, function (data) {
// Handle server data, passed with Ok("Here's my data")
});
return false;
});
Upvotes: 0