2

I'm new to Play 2.3 and having a lot of trouble with forms and data binding. Here's a scenario that's costing me a lot of headaches:

I have a model like this f.e. (annotations left out):

public class User extends Model {
    public Integer id;
    public String name;
    public String anyOtherField;
}

Now I have a form in a scala.view where I want to be able to change the user's name:

@(userForm: Form[User])
@helper.form(action = routes.UserController.save()) {
    @helper.inputText(userForm("name"), '_label -> "Name")
}

I call this view in my Controller like this:

Form<User> userForm = Form.form(User.class).fill(myUser);
return ok(views.html.usermgmt.useredit.render(userForm));

When the user submits the form I'm back in my Controller like that:

public static Result save() {
    Form userForm = Form.form(User.class).bindFromRequest();
    User user = userForm.get()
}

However, and now comes my big surprise: The resulting User from userForm.get() has no fields filled other than "name". No "id", no "anyOtherField". What is the point in having that data binding when the resulting object is totally useless for further processing? Am I missing something?

If I don't miss something then I have to write a lot of boilerplate code in order to do the databinding myself:

  • Either manually assign the changed fields to the real "user" object (which I have to re-fetch within save() first)
  • Or include hidden fields for all the fields in the model. In that case I better not forget updating the form if I add another field to the model.

Please tell me I'm missing sth.!?

  • You are only adding the name field to the form, so when your browser sends the data (only the user name) Plays parses only that. The idea of binding is to bind the data you get from the browser to your objects. [This answer](http://stackoverflow.com/a/10380119/1205368) may help you avoid some boilerplate – Salem Oct 13 '14 at 10:16

1 Answers1

0

Binding parameters manually is (at least from the security point of view) the best way to go. Imagine your User Model has a field that saves security-relevant information. For example isAdmin in a very simple model. If you would bind your forms from the User class that your backend uses to store the information in the database, an attacker would easily be able to make himself an admin by adding an additional parameter to the save request.

The binding mechanism isn't meant to be used with backend data-models. This seems to be a misunderstanding that isn't described clearly in the documentation. I've filed a bug once because of that security vulnerability but the developers made clear that using backend models to bind form data is not the way form binding should be used. See this bug-report for details: https://github.com/playframework/playframework/issues/2358