I want to have my “ok” button (windowCommit) in an Editor disable if no change has been done in the fields.
I have an Editor page, which extends AbstractEditor. It has lot of fields from a datasource. If you click on “ok”, all the fields will be saved in the database. If any change has been done in the fields, the object is also saved to the database.
I will that they don’t save if no change has been done in any field.
My first idea is:
If datasource has been changed
Then enable button
Problem, the datasource is only refreshed when the button is clicked, not only when anything is changed in the fields.
Antoher possibility will be, to attach a listener of each field and detect a change in this field, but I have lot a fields, and I will have then lot of listeners.
This can be achieved using datasource listeners: you can disable the OK button and enable it only after the datasource changes, for example:
public class EmployeeEdit extends AbstractEditor<Employee> {
@Inject
private Button windowCommit;
@Inject
private Datasource<Employee> employeeDs;
@Override
public void ready() {
windowCommit.setEnabled(false);
employeeDs.addItemPropertyChangeListener(e ->
windowCommit.setEnabled(employeeDs.isModified())
);
}
}
Pay attention that windowActions frame is not fully initialized when the init() method is invoked, so you can start working with it in the postInit() or ready() method of the screen lifecycle.
That don’t work. I have ever tried, but the proble is that the listener is not called when a field is modified, then the button will never be enabled. I don’t know when the listener is called, but I suspect only when the windowCommit button is clicked, then the datasource is updated and not only when the field is modified
The datasource is updated when the input field looses its focus. If needed, you can additionally use, for example, TextChangeListener that will be triggered even if the field still has focus.
Normally, the datasource is updated when you click outside the field or in another field. If that does not work in your case, could you please share a small sample project or, at least, your screen controller and descriptor code.