Form seq(text) binding
I'm trying to bind a seq of text to a scala Form. What I have so far is the following code:
val registerForm = Form[User](
mapping(
"login" -> text,
"password" -> text,
"roles" -> seq(text)
) {
(login, password, roles) => User(login = login, password = password, roles = roles)
} {
user => Some((user.login, user.password, user.roles))
})
My HTML form select is:
<select id="roles" name="roles" multiple="multiple">
<option value="ADMIN">Admin</option>
<option value="TESTER">Tester</option>
</select>
Login and password are binded correctly. My problem is that the seq of roles is always empty.
I've checked in the request object passed to the controller method and (if selected) both roles are there - they are just not binded correctly in form object.
Any ideas?
Edit:
I also posted my question at play-framework Google Group (https://groups.google.com/forum/#!topic/play-framework/KcbiF9K3d8w) and received answer there. The solution is to give select a name: "roles[]" instead of "roles".
Figured it out.
The solution is to give select a name: "roles[]" instead of "roles".
A Java Play 2.3.7 example of binding a Play Form
to a select
with the multiple
attribute:
<select name="bar[]" multiple>
<option value="bar-1">Bar</option>
<option value="bar-2">Bar Bar</option>
<option value="bar-3">Bar Bar Bar</option>
</select>
With a Form
:
public class FooForm {
public List<String> bar;
}
And Controller
binding:
FooForm fooForm = Form.form(FooForm.class).bindFromRequest().get();
Logger.info(fooForm.bar.get(0));
Logger.info(fooForm.bar.get(1));
I've tested with arrays (ie String[]
) and it only seems to work with List<>
.
Hope this helps.
Note: Oddly, this only works when the Form
class ( FooForm
) is in the same package as the controller, or in the same class and static
. This appears to be a bug.
If you want to use a different package (ie controllers.forms
), then you need getters and setters in your form class:
public class FooForm {
private List<String> bar;
public List<String> getBar() { return bar; }
public void setBar(List<String> bar) { this.bar = bar; }
}
链接地址: http://www.djcxy.com/p/74872.html
上一篇: 警告开发人员在java中调用`super.foo()`
下一篇: 形成seq(文本)绑定