我拼命地尝试从表单提交中接收值列表并将其绑定到对象列表。
检索单行有效:
//class
case class Task(name: String, description: String)
val taskForm: Form[Task] = Form(
mapping(
"name" -> text,
"description" -> text
)(Task.apply)(Task.unapply)
)
//form
<tr>
<td><input name="name" type="text" class="span2" placeholder="Name..."></td>
<td><textarea name="description" class="autoexpand span7" rows="1" placeholder="Description..."></textarea>
</td>
</tr>
//receiving action:
val task = taskForm.bindFromRequest.get
但现在我想提交多个类型为task的对象,例如:
<tr>
<td><input name="name[0]" type="text" class="span2" placeholder="Name..."></td>
<td><textarea name="description[0]" class="autoexpand span7" rows="1" placeholder="Description..."></textarea></td>
</tr>
<tr>
<td><input name="name[1]" type="text" class="span2" placeholder="Name..."></td>
<td><textarea name="description[1]" class="autoexpand span7" rows="1" placeholder="Description..."></textarea></td>
</tr>
做一个 taskForm.bindFromRequest.get 现在失败了。
有人想出一个解决方案吗?或者你处理这种情况完全不同?
答案 0 :(得分:17)
好吧,谢谢你暗示我再次看一下这些文档,我已经看过它们了,但是从来没有能够把它组合起来让它起作用。我想这是因为我是一个scala noob。 但是,在给它一些时间之后我才开始工作,这是我的解决方案:
//classes
case class Task(name: String, description: String)
case class Tasks(tasks: List[Task])
val taskForm: Form[Tasks] = Form(
mapping(
"tasks" -> list(mapping(
"name" -> text,
"description" -> text
)(Task.apply)(Task.unapply))
)(Tasks.apply)(Tasks.unapply)
)
//form
<tr>
<td><input name="tasks[0].name" type="text" class="span2" placeholder="Name..."></td>
<td><textarea name="tasks[0].description" class="autoexpand span7" rows="1" placeholder="Description..."></textarea></td>
</tr>
<tr>
<td><input name="tasks[1].name" type="text" class="span2" placeholder="Name..."></td>
<td><textarea name="tasks[1].description" class="autoexpand span7" rows="1" placeholder="Description..."></textarea></td>
</tr>
最后做一个:
val tasks = taskForm.bindFromRequest.get
检索任务列表。
答案 1 :(得分:1)
来自playframework文档page:
重复值
表单映射还可以定义重复值:
case class User(name: String, emails: List[String]) val userForm = Form( mapping( "name" -> text, "emails" -> list(text) )(User.apply, User.unapply) )
当您使用这样的重复数据时,发送的表单值 浏览器必须命名为电子邮件[0],电子邮件[1],电子邮件[2]等