How can I update only a particular set of fields to the database with Play? Currently I have a User
model that contains a specific field, let call it: isAdministrator
:
private boolean isAdministrator;
And I have the accessor methods:
/**
* @return the isAdministrator
*/
public boolean isAdministrator() {
return isAdministrator;
}
/**
* @param isAdministrator
* the isAdministrator to set
*/
public void setAdministrator(boolean isAdministrator) {
this.isAdministrator = isAdministrator;
}
But when I change the username, via a form where isAdministrator
is NOT included, Play resets my User objects and sets the value 0
for this user?
So, how can I update only the changed fields?
I don't directly answer to your question, but instead of having a boolean indicating that your User is an admin or not, I would create an Admin
class which inherits from the User.
public class Admin extends User {
....
}
It's the "S" of SOLID ;-)
EDIT:
In the controller, you can load the old value from the database before updating with the form values:
...
User userFromDB = User.findById(anId);
User userFromForm = userForm.get();
// set previous value
userFromForm.setArchived(userFromDB.getArchived());
User.update(userFromForm);
...
In addition to nico's answer I only can add, that you don't need to use Form
class in every case. Sometimes it's enough to just get data from request and update your object manually which useful especially with ajax calls when you have detailed level of intermediate saving (see example of use of the DynamicForm it can be even shorter and also you can validate it yourself:
public static Result updateName(Integer id){
User user = User.find.byId(id);
user.name = form().bindFromRequest().get("name");
user.update(id);
return ok();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With