使用播放表单对象检查表单字段是否已更改

时间:2014-12-30 14:10:01

标签: java playframework playframework-2.3

如果播放框架中的表单字段的内容发生了变化,有没有办法直接检查?

例如我的Device.java是这样的:

class Device{
  String name;
  String type;}

然后在我的控制器的某个地方,我有一种类型的设备。如果boundForm属性的值发生了变化,有没有办法使用name进行检查?

public class Devices extends Controller {

private static final Form<Device> deviceForm = Form.form(Device.class);

public static Result details(Device device) {
    if (device == null) {
        return notFound(String.format("Device does not exist. "));
    }
    Form<Device> filledForm = deviceForm.fill(device);
    return ok(views.html.devices.details.render(filledForm));
}


public static Result save() {
    Form<Device> boundForm = deviceForm.bindFromRequest();
    ...
    [here]
    ...
}
}

注意:详细信息方法会向用户显示填充的表单,用户可能会也可能不会更改值,然后按“保存”按钮,将调用save()方法。

1 个答案:

答案 0 :(得分:1)

用最短的字Form<T>无法检查字段是否被更改,它只是在请求之间无状态并检查它只需要从中获取记录数据库和比较字段,按字段。

此外,您不应该依赖客户端验证,因为它主要用于装饰,不是为了安全。请记住,使用常见的webdev工具可以很容易地操作或省略它。

最后,你不应该从Form验证可能性中退出,因为它是非常方便的工具,而是你可以配合它,即它可以是这样的:

public static Result save() {
    Form<Device> boundForm = deviceForm.bindFromRequest();
    if (boundForm.hasErrors()){
        return badRequest(devices.details.render(boundForm));
    }

    Device boundDevice = boundForm.get();
    Device existingDevice = Device.find.byId(boundDevice.id);

    if (boundDevice.name.equals(existingDevice.name)){
        boundForm.reject("Contents are identical");
        return badRequest(devices.details.render(boundForm));
    }

    // else... form hasn't errors, name changed - should be updated...
    boundDevice.update(boundDevice.id);
}  

所以你可以在你的视图中显示它,例如:

@if(yourForm.error("identicalContent")!=null) {
    <div class="alert alert-danger">@yourForm.error("identicalContent").message</div>
}

正如您从此示例中看到的那样 - 如果您只想跳过UPDATE查询,如果没有更改 - 以节省资源 - 它没有意义,因为您需要进行SELECT查询相比。在其他情况下(例如,只有在更改时才进行额外的记录)上面的代码段是正确的解决方案。