sve*_*eri 4 forms binding scala playframework-2.0
我拼命地尝试从表单提交中接收值列表并将其绑定到对象列表.
什么有效是检索单行:
//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
Run Code Online (Sandbox Code Playgroud)
但是现在我想提交多个类型为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>
Run Code Online (Sandbox Code Playgroud)
现在执行taskForm.bindFromRequest.get失败.
有人想出一个解决方案吗?或者你处理这种情况完全不同?
sve*_*eri 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>
Run Code Online (Sandbox Code Playgroud)
最后做一个:
val tasks = taskForm.bindFromRequest.get
Run Code Online (Sandbox Code Playgroud)
检索任务列表.