Reputation: 984
Is there any way to check directly, if the content of a form field in play framework has changed?
for example my Device.java
is something like this:
class Device{
String name;
String type;}
and then somewhere in my controller, I have a form of type Device. is there any way to check using boundForm
if the value of the name
property has changed?
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]
...
}
}
note: details method will show the user the filled form, user may or may not change the values, and then by pressing a Save button , the save() method will be called.
Upvotes: 0
Views: 491
Reputation: 55798
In shortest words Form<T>
isn't able to check if fields are changed it's just stateless between request and to check it you just need to get record from DB and compare field, by field.
Also you shouldn't rely on client-side validation as it's mainly for cosmetic, NOT for safety. Remember that it can be manipulated or omitted quite easy with common webdev tools.
Finally you shouldn't resign from Form
validation possibilities,as it's very handy tool, instead you can cooperate with it, i.e. it can be something like:
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);
}
So you can display it in your view i.e.:
@if(yourForm.error("identicalContent")!=null) {
<div class="alert alert-danger">@yourForm.error("identicalContent").message</div>
}
As you can see from this sample - if you want just to skip UPDATE
query if no changes - to save resources - it does not make sense, as you need to make SELECT
query anyway to compare. In other cases (like i.e. additional logging ONLY if changed) above snippet is correct solution.
Upvotes: 1