Nested form in Play! Scala 2.2

不羁的心 提交于 2019-12-25 01:55:43

问题


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 inputs 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!