kqdtran
kqdtran

Reputation: 43

List mapping in Play2's form

I'm trying to create a form with multiple textarea, each goes with a corresponding checkbox. Basically, the application works as "If yes (the checkbox is checked), leave the textarea blank. Otherwise, fill in your explanation on why do you think it's wrong".

In models, I have

case class AnswerMapping(id: Long, status: Option[String], result: Option[String]

val form = Form[Seq[Answers](
  mapping(
   "details" ->
      list(mapping(
        "id" -> longNumber,
        "status" -> optional(text),
        "result" -> optional(text)
      )(AnswerMapping.apply)(AnswerMapping.unapply)
  ))(apply)(unapply)
)

In views, I have

@helper.form(action = controllers.conflict.routes.Answer.updateAnswer(ans.id()) {
  <div class="row-fluid">
    <div class="span12">
      @ans.details.get.zipWithIndex.map { case(detail, index) =>
        @helper.textarea(
          form(("details[" + index + "].result")),
          'class -> "input-xlarge resizable",
          'id -> ("box" + index),
          '_label -> "")
      }
    </div>
    <div class="controls">
      <input value="Submit" type="submit" class="btn btn-primary">
    </div>
  </div>
}

The rendered HTML looks like <textarea id="box0" name="details[0].result" class="input-xlarge resizable" id="box0"></textarea>

However, when I submitted the form, I was redirected back to the same page. This is probably because I have this in my controllers, which means there's error in my form

Ans.form.bindFromRequest.fold(
  formWithErrors => Ok(views.html.answer.edit(answer, formWithErrors)),
  ans => { // save the answer }

My question:

  1. Is the above, details[0].result the right syntax to access an element in a form's list
  2. I don't quite understand why my form has errors. The two fields that needs to be filled in are marked as optional, simply because sometimes a checkbox is not checked, and sometimes the answer box is left blank. Is this perhaps because of the id field? I already set it in my apply/unapply method, so I'm not sure what I'm missing.

Thanks for all the input.

Upvotes: 3

Views: 721

Answers (1)

Mark Simon
Mark Simon

Reputation: 412

see document:Repeated values

@helper.repeat(myForm("emails"), min = 1) { emailField =>
    @helper.inputText(emailField)
}

Upvotes: 0

Related Questions