Im trying to make an order form with Play 2 and Scala.
Here is what it was before grouping:
<table>
@items.zipWithIndex.map {
case (item, index) =>
@itemRow(item, index)
}
</table>
itemRow definition
@itemRow(index: Int, item: Item) = {
<tr>
<td>
@(index+1)
</td>
<td>
@item.name
</td>
<td>
<input type="hidden" name="@requestForm("items")("[" + index + "]")("itemId").name" value="@item.id">
<input type="text" name="items[@index].count" value="@requestForm("items")("[" + index + "]")("count").value">
</td>
</tr>
}
At first I tried naive implementation
@items.groupBy(item => item.category).map {
case (categoryId, itemsInCategory) =>
<table>
@itemsInCategory.zipWithIndex.map {
case (item, index) =>
@itemRow(item, index)
}
</table>
}
But there is a problem, indexes in each category starts with 0.
So, http request is something like that:
# category 1
items[0].id = 1
items[0].count = 1
items[1].id = 2
items[1].count = 2
# category 2
items[0].id = 3
items[0].count = 1
items[1].id = 4
items[1].count = 5
And it is causes to values being overriden.
I need my indexes for be consecutive within the form, like this:
# category 1
items[0].id = 1
items[0].count = 1
items[1].id = 2
items[1].count = 2
# category 2
items[2].id = 3
items[2].count = 1
items[3].id = 4
items[3].count = 5
So there is questions
For functional programmers:
- Can I make index variable shared for all groups?
For Play 2.0 or web programmers:
- Is there another way to make form with variable count of repeated values?
- How to avoid sending this bunch of items with 0 count?
I have no experience with Play so I can’t comment on the Play specific questions (maybe it already provides helpers for what you want), but on the scala librayr alone you can do something like this:
The idea is to first sort the items by category and then zip them with the corresponding indexes. Then only you group them by category (which should be fast as the list is already sorted).