Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update / save only changed fields

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?

like image 716
adis Avatar asked Feb 19 '23 17:02

adis


2 Answers

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);
...
like image 122
ndeverge Avatar answered Feb 28 '23 16:02

ndeverge


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();
}
like image 20
biesior Avatar answered Feb 28 '23 18:02

biesior