mardi 6 février 2018

Play framework + scala: Process checkbox list and selected items

I have a list of items I want to show as checkboxes, and I have a list of the items the user actually has selected previously and that I have stored in the database. So what I need is to show all the items but only mark as checked the selected items:

  • [ ]item1
  • [ ]item2
  • [x]item3
  • [x]item4

Here is my mapping:

def formMapping: Mapping[Data] = {
        mapping(
            "selectedItems" -> play.api.data.Forms.list(String)
        )(Data.apply)(Data.unapply)
    }

And my html:

@(theForm: Form[DataForView])

@for((itemValue, itemName) <- allItems) {
        <input type="checkbox" name="selectedItems" value="@itemValue"/>@itemName<br/>
    }

I'm using the name "selectedItems" so it maps to the form field. I though about using the @checkbox helper but then I would only see the selectedItems, not all items.

I've considered other options, for instance, eliminating "selectedItems" and having a list of all items with a Boolean that indicates if it is selected or not. But that means that I would have to cross the items with the selectedItems and I was hoping there would be a better way.

Any ideas?




Aucun commentaire:

Enregistrer un commentaire