[2.0] Binding multiselect in form to ManyToMany from request

645 views
Skip to first unread message

P-A Söderqvist

unread,
Mar 29, 2012, 6:26:55 PM3/29/12
to play-fr...@googlegroups.com
Hi
If I have the following entities:

@Entity
public class Unit extends Model {

@Id
public Long id;

 ... 

public static Map<String, String> getAllAsMap() {
 ... // Returns map with id as key
}
}

@Entity
public class User extends Model {

@Id
public Long id;

@ManyToMany
public Set<Unit> units;

 ... 
}

and the following view:

@(userForm: Form[User], availableUnits: Map[String, String]) 

@main("Add User", "Users") {
@helper.form(action = routes.Users.create) { 
<fieldset>
...
@helper.select(userForm("units.id"), options(availableUnits), 'multiple -> "multiple", '_label -> "Unit", '_error -> userForm.error("units.id"))
</fieldset>
... 
}
}

and the following controller with methods to render and submit the form

public class Users extends Controller {
... 
public static Result addForm() {
return ok(addFormView.render(form(User.class), Unit.getAllAsMap()));
}

public static Result create() {
Form<User> userForm = form(User.class).bindFromRequest();

validateForm(userForm);

if (userForm.hasErrors()) {
return badRequest(addFormView.render(userForm, Unit.getAllAsMap()));
} else {
userForm.get().save();
return redirect(controllers.routes.Users.list());
}
}
...  
}

Is it possible to bind a multi select list automatically into a ManyToMany relationship from the request like this?
I have no problem binding to single string fields, single enum fields or ManyToOne fields.

br
P-A Söderqvist


Message has been deleted

Drevlyanin

unread,
Apr 3, 2012, 9:31:01 AM4/3/12
to play-fr...@googlegroups.com
Met with the same problem. I do not know how to solve it beautifully. :(

András Pálinkás

unread,
Apr 12, 2012, 11:36:32 AM4/12/12
to play-fr...@googlegroups.com
Any update on this one?

On Tue, Apr 3, 2012 at 3:31 PM, Drevlyanin <drevl...@gmail.com> wrote:
Met with the same problem. I do not know how to solve it beautifully. :(

--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To view this discussion on the web visit https://groups.google.com/d/msg/play-framework/-/zSjErJE1g8kJ.

To post to this group, send email to play-fr...@googlegroups.com.
To unsubscribe from this group, send email to play-framewor...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/play-framework?hl=en.

Kevin Bosman

unread,
Apr 12, 2012, 9:02:33 PM4/12/12
to play-fr...@googlegroups.com
There's no automatic way of handling this that I know of.
Please refer to my previous answer on this topic for some tips:
https://groups.google.com/d/msg/play-framework/oiUqGQ8IMCo/yF1vLNX1VxsJ
Reply all
Reply to author
Forward
0 new messages