我正在使用 Play 2.1 我使用辅助字段构造函数制作了一个选择下拉框。下拉框有 3 个字段,默认:“选择性别”、男性和女性。如何确保用户选择男性或女性之一,而不是默认值?(必填下拉字段)
问问题
2178 次
1 回答
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">
}
}
另请参阅这篇文章作为参考:在 Play Framework 2.0 模板中使用选项助手
于 2013-03-04T12:40:34.750 回答