Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a array form field with Playframework scala [closed]

The form I have to handle has something like this:

<label for="features_1">
  <input type="checkbox" id="features_1" name="features[]" value="4"> foo
</label>
<label for="features_2">
  <input type="checkbox" id="features_2" name="features[]" value="8"> bar
</label>

I can get the array like this

request.body.asFormUrlEncoded.get("features[]")

which gives me when both items are selected List(4, 8)

But when I try to bind this in a form

case class MyFeatures(features: Seq[Long])

val myForm = Form (
    mapping(
      "features" -> seq(longNumber)
    )(MyFeatures.apply)(MyFeatures.unapply)
)

I always get an empty sequence, same with "features[]"

EDIT

The above example actually works, the issue was somewhere else. Upon binding play translates the features to feature[0]=4 and features[1]=8 which is then handled correctly in the seq(...) or list(...) mappings

like image 621
Somatik Avatar asked Apr 16 '14 09:04

Somatik


1 Answers

Try:

<label for="features_1">
  <input type="checkbox" id="features_1" name="features[0]" value="4"> foo
</label>
<label for="features_2">
  <input type="checkbox" id="features_2" name="features[1]" value="8"> bar
</label>

EDIT

Or:

myForm.bind(myForm.bindFromRequest.data + ("features"-> request.body.asFormUrlEncoded.get("features[]"))).fold(
...
)

This will bind all other fields from request directly, and then when it comes to features, they are going to be added manually. If you don't need to bind more data then just write:

myForm.bind("features"-> request.body.asFormUrlEncoded.get("features[]")).fold(
...
)
like image 174
Peter Avatar answered Sep 21 '22 22:09

Peter