Unable to implement specific functionality with Datasource Listeners

Hi,
I am trying to implement an accounting-related basic scenario but I can’t get the required result. According to my scenario, there is a Journal screen (see attached file) where the user is allowed to enter an amount either in the field “Debit Amount” or “Credit Amount”. When the field “Debit Amount” is filled in by the user, then the field “Credit Amount” should be set to zero while the field “Amount” will be equal to “Debit Amount” value. If the user, enters a value in the field “Credit Amount” , then the field “Debit Amount” should be set to zero and the field “Amount” should have the value minus “Credit Amount”. I tried to implement the aforementioned scenario using the datasource listener ItemPropertyChangeListener for both fields “Debit Amount” & “Credit Amount”. Unfortunately, both fields are set to zero since the listeners are called for both fields!

Do you have any idea about how I could resolve this problem?

Regards,
George

GeneralJournal

Hi George,

You can easily resolve the problem by introducing a boolean field that will prevent entering into listener second time.

Provided that you have an entity with three fields:

public class Foo extends StandardEntity {

    @Column(name = "FIELD1")
    protected BigDecimal field1;

    @Column(name = "FIELD2")
    protected BigDecimal field2;

    @Column(name = "FIELD3")
    protected BigDecimal field3;
    
    //...
}    

the listener setting a value to field3 either from field1 or field2 can look as follows:

public class FooEdit extends AbstractEditor<Foo> {

    @Inject
    private Datasource<Foo> fooDs;

    private boolean changing;

    @Override
    public void init(Map<String, Object> params) {
        fooDs.addItemPropertyChangeListener(e -> {
            if (changing)
                return;
            changing = true;
            try {
                getItem().setField3((BigDecimal) e.getValue());
                if (e.getProperty().equals("field1")) {
                    getItem().setField2(BigDecimal.ZERO);
                } else if (e.getProperty().equals("field2")) {
                    getItem().setField1(BigDecimal.ZERO);
                }
            } finally {
                changing = false;
            }
        });
    }
}

Thank you very much!