问题
I have read several times the documentation but I still have problems with my nested form in Play! Scala 2.2 (detailed further).
Here is my form :
<form method="post" action="/admin/test2">
first name : <input type="text" name="firstname"> <br>
info 0 : <input type="text" name="label[0]"> <br>
info 1 : <input type="text" name="label[1]"> <br>
<input type="submit" value="test nested form" />
</form>
And the case classes corresponding :
case class Contact(firstname: String,
informations: Seq[ContactInformation])
case class ContactInformation(label: String)
val contactForm: Form[Contact] = Form(
mapping(
"firstname" -> nonEmptyText,
"informations" -> seq(
mapping(
"label" -> nonEmptyText
)(ContactInformation.apply)(ContactInformation.unapply)
)
)(Contact.apply)(Contact.unapply)
)
def saveContact = Action { implicit request =>
contactForm.bindFromRequest.fold(
formWithErrors => Ok("error"),
contact => {
println(contact)
Ok("Done")
}
)
}
I don't get any errors, but the contact that I get from the form (printed with println(contact)
) has an empty informations field, i.e. it looks like this : Contact(h,List())
The error comes probably from the html
part since I have followed to the letter the documentation from this page : play! scala forms documentation
but I can’t figure it out.
回答1:
The field names of the input
s should use the full path in the Form
. label
appears within the informations
Mapping
, and informations
is the sequence, not the label
, so you should use informations[0].label
instead of label[0]
.
Your view should look like this:
first name : <input type="text" name="firstname"> <br>
info 0 : <input type="text" name="informations[0].label"> <br>
info 1 : <input type="text" name="informations[1].label"> <br>
来源:https://stackoverflow.com/questions/28507983/nested-form-in-play-scala-2-2