我正在使用Play 2.1 我使用辅助字段构造函数创建了一个选择下拉框。 下拉框有3个字段,默认:“选择性别”,男性和女性。 如何确保用户选择男性或女性,而不是默认值? (必填的下拉字段)
答案 0 :(得分:1)
我正在使用 Play!Framework 2.1.0 ,下面是您问题的简单解决方案:
模型应该是这样的:(以下是您问题的简单模型)
package models;
import play.data.validation.Constraints;
public class Gender {
// This field must have a value (not null or not an empty string)
@Constraints.Required
public String gender;
}
控制器应该是这样的:
/** Render form with select input **/
public static Result selectInput() {
Form<Gender> genderForm = Form.form(Gender.class);
return ok(views.html.validselect.render(genderForm));
}
/** Handle form submit **/
public static Result validateSelectInput() {
Form<Gender> genderForm = Form.form(Gender.class).bindFromRequest();
if (genderForm.hasErrors()) { // check validity
return ok("Gender must be filled!"); // can be bad request or error, etc.
} else {
return ok("Input is valid"); // success validating input
}
}
模板/视图应如下所示:
@(genderForm: Form[models.Gender])
@import views.html.helper._
@main(title = "Validate Select") {
@form(action = routes.Application.validateSelectInput()) {
@********** The default value for select input should be "" as a value *********@
@select(
field = genderForm("gender"),
options = options("" -> "Select Gender", "M" -> "Male", "F" -> "Female")
)
<input type="submit" value="Post">
}
}
另请参阅此帖子:Use of option helper in Play Framework 2.0 templates