0

I have the following form with repeating items:

 @(adverts: List[models.AdvertModel])
 @if(adverts.size() > 0 && adverts != null) {
    @helper.form(action = routes.UserController.editAdvert()) {
        @for( (advert, index) <- adverts zip (Stream from 0)) {
            <div>@adverts.get(index).title</div>
            <button type="submit" name="delete" id="delete_@index">delete</button>    

        }
     }

and this controller:

    public Result editAdvert() {
    String[] indices =   request().body().asFormUrlEncoded().get("delete");
    if (indices != null) {
        // delete advert
        }
    return ok();
}

I would like to be able to delete adverts according to their ids but with the current code my array contains a String "delete" instead of i.e. "delete_0". How do I get the index of the clicked button?

istern
  • 363
  • 1
  • 4
  • 13
  • I don't know Play forms well (I try to avoid html forms), but adding HTTP messages to the question might help. Usually I get them using my browser devtools – Tair Jan 23 '16 at 17:36

1 Answers1

0

I finally got it:

tldr:

add value="delete_@index" to the button.

longer answer:

The value returned by request().body().asFormUrlEncoded().get("delete") is saved in the value attribute of the button with name="delete" in the scala template. Therefore, by adding a value="delete_@index" to the button, we will get a String such as delete_0.

As @danielnixon commented, this is not a play-specific behaviour, but simply how html forms work.

istern
  • 363
  • 1
  • 4
  • 13
  • 1
    Nothing Play Framework specific here. This is just how HTML forms work. See e.g. http://stackoverflow.com/a/2129364/2476884 – danielnixon Jan 24 '16 at 22:43