简体   繁体   English

如何从Play框架中的表单读取日期

[英]How to read date from form in play framework

I have Date expirationDate field in my class. 我的班级中有Date expirationDate字段。 I also have select dropdown menu in my form with day/month/year 我还可以在表单中选择带日期/月份/年份的下拉菜单

<select class="form-control" value="@form("day")" >
            <option>dd</option>
            @for(a <- 1 to 31) {
            <option>@a</option>
            }
</select>
<select class="form-control" value="@form("month")" >
            <option>mm</option>
            @for(a <- 1 to 12) {
            <option>@a</option>
            }
</select>
<select class="form-control" value="@form("year")" >
            <option>yyyy</option>
            @for(a <- 2014 to 2100) {
            <option>@a</option>
            }
</select>

How can i bind this data to java.util.Date type in controller? 我如何将此数据绑定到控制器java.util.Date类型? More specifically 进一步来说

public static Result createScenarioPOST() throws ParseException {
    User user=User.find
            .where().eq("email", session("email")).findUnique();

    Form<Creation> createForm = Form.form(Creation.class)
            .bindFromRequest();
    if (createForm.hasErrors()) {
        return badRequest(createScenario.render(createForm, user));
    } else {
        return redirect(routes.Application.index());
    }
}

The difficulty here comes from having separate input fields for day/month/year fields. 这里的困难来自于针对日/月/年字段的单独输入字段。 Since Play's Form s map to individual values, you cannot use them to map to a single value. 由于Play的Form映射到单个值,因此您不能使用它们映射到单个值。

Use a Form to map (and validate!) the individual values, then construct the Date the way you normally would create a Date . 使用Form来映射(并验证!)各个值,然后以通常创建Date的方式构造Date

An easier way to do this is by having the date be a single form value, for example by using an <input type="date"> input field. 一种简单的方法是使日期为单一表单值,例如使用<input type="date">输入字段。 If your really must have separate fields and really want to bind it to a single field, you could consider using JavaScript to concatenate the separate fields into a single value on form submit. 如果您确实必须具有单独的字段,并且确实要将其绑定到单个字段,则可以考虑使用JavaScript在表单提交时将单独的字段连接为单个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM