behzad
behzad

Reputation: 984

Passing a List of objects from view to Controller in play framework

In my play(FOR JAVA) app, I have a list of objects (java.util.List) that will be passed to a view and will be shown to the user. Then user can may or may not delete some of the objects in the list, and after that, I want to pass the edited list back to the Controller BUT I can't do the last part(passing from view to controller).

Because my list might be big, I don't want to do that with a GET (GET is also kind of unsafe?!) and don't know how to do it with a POST, (or is there any other solution?)

So it would be great if I could get some help with this.

The objects inside my list are from this type:

public class CalObj {

   private String pdfFileName;
   private String serialNo;
   private Date calDate;
   private Device device;
}

UPDATE: thanks @biesior , my View(calExtractionResults.scala.html) now looks like this:

    @for(calObj <- calObjList) {
      <tr>
        <td> @calObj.getPdfFileName</td>
        <td> @calObj.getSerialNo</td>
        <td> @calObj.getDevice.name</td>
        <td> @calObj.getDevice.calDateToString()</td>
        <td> @calObj.getCalDate</td>
        <td>
            <form action="@DateExtractorContr.updateList(calObjList, calObj)" method="POST">
                <input type="hidden" name="serialNo" value="@calObj.getSerialNo"/>
                <input type="submit" value="Delete"/>
            </form>
        </td>

      </tr>
    }

and this is in my Controller:

public static Result updateList(List<CalObj> calObjs, CalObj objToDel){
    List<CalObj> newList = calObjs;
    newList.remove(objToDel);
    return ok(calExtractionResults.render(newList));
}

but when I open the related page, there are problems:

  1. with the code above, I get: [ConcurrentModificationException: null]
  2. if I replace the updateList function with a dummy function that does not make concurrent exception, before showing the page, the program goes through that dummy function. before I even click on the Delete button.

Upvotes: 0

Views: 1503

Answers (1)

biesior
biesior

Reputation: 55798

That's simple:

Iterate list with @for statement wrapping each element with separate form:

@for(item <- yourList) {
    <h1>@item.name</h1>
    <form action="/link/to/delete/action" method="POST">
       <input type="hidden" name="id" value="@item.id"/>
       <input type="submit" value="Delete"/>
    </form>
}

So after deleting the item you can redirect to the list view again.

As you can see you need some unique ID (maybe serialNo keeps the role in your case, dunno).

Edit: Of course you can also create one form witch checkboxes as array, to send it at once if you want to delete many elements.

Upvotes: 1

Related Questions