Thursday, November 15, 2012

Wednesday, November 14, 2012

Play 2 Framework Limit Request Data

My form had more fields than I wanted to save (lists of multiple models). And I only wanted to validate and save one data set (list of models) at a time.

To solve this I added one submit button per list of models and a name tag, with the id of my model list, to each submit button:

<input type="submit" name="@modellist.id" value="Save Model @modellist.id">

In my controller I now wanted to remove all the fields that were irrelevant before validation (So I wouldn't get any errors on those fields). From all the submitted models I wanted to fetch all models that matched my submit button's modelid:

(Note: To accomodate the lists of models, I have created a class which contains a map of all models submitted by the form, so thats why I'm working with maps. If you have a simpler setup this idea might be more easily done)

Form<ModelMap> modelMapForm = form(ModelMap.class);

// Remove unwanted models depending on which submit button has been pressed.
DynamicForm requestData = form().bindFromRequest(); // Doesn't try to match values to a "model"
Form<ModelMap> filledModelMapForm = ModelMapForm.bindFromRequest();
ModelMap allModelMap = filledModelMapForm.get();
ModelMap wantedModelMap = new ModelMap();
for (int modelid : modelids) {
    // Check if modelid is in POST data, if yes than that button was pressed and we want that data.
    if (requestData.get(""   modelid) != null) {
        for (Map.Entry<String, Model> entry : allModelMap.models.entrySet()) {
            if (entry.getKey().endsWith(""   modelid)) {
                wantedModelMap.models.put(entry.getKey(), entry.getValue());
            }
        }
    }
}
// Place wanted values in filledModelMapForm for validation and saving
filledModelMapForm = filledModelMapForm.fill(wantedModelMap);
// Place all values in allModelMapForm so that they are shown in case of errors
Form<ModelMap> allModelMapForm = ModelMapForm.bindFromRequest();

if (filledAnswerMapForm.hasErrors()) {
    allModelMapForm.reject("Error, please correct it.");
    return badRequest(view.render(<other values>, allModelMapForm));
}
else {
    ModelMap saveModelMap = filledModelMapForm.get();
    // Process form...
}


Maybe this solves your problem or helps you solve it. :) If you find a more elegant way, please don't hesitate to tell me below.

Source: https://groups.google.com/forum/?fromgroups=#!topic/play-framework/TRzjAwVvVEM