Can I have automatically calculated persistent fields in a DataGrid?

Hi,
I have a dataGrid where some persistent fields are calculated based on the values of other fields. For example, there is a purchase invoice line where the field ‘Total Line Amount’ is the product of the Quantity & Unit Cost columns. An option probably could be to use a non-persistent calculated field for the Total Amount, but I need the user to be able to modify the value of this field if required. I just tried to use a datasource listener to get the current dataGrid row and do the required calculations but I can’t get the required result. So, I wish to ask you how could I get the current dataGrid row and do the necessary column update?

Regards,
George

Hi,

According to your description, if I understand you correctly, I consider that your requirement is not related to the DataGrid itself. So, I can suggest to add a CollectionChangeListener and update your item within it. For example:

linesDs.addCollectionChangeListener(e -> {
	if (Operation.ADD.equals(e.getOperation())
			|| Operation.UPDATE.equals(e.getOperation())) {
		for (OrderLine line : e.getItems()) {
			linesDs.getItemNN(line.getId())
					.setTotalAmount(line.getProduct().getPrice().multiply(line.getQuantity()));
		}
	}
});

In case of a non-persistent field, you can add a method with @MetaProperty annotation and return calculated value. You can read about @MetaProperty in the documentation.

Also, to represent calculated value, you can add a generated column to a DataGrid. Take a look at this sample.

Regards,
Gleb

Hi Gleb,
Thank you for your reply. I have added the CollectionChangeListener but I’ve noticed that it is not called during inline editing operation in the datagrid. Am I missing something? The request of my client is to make use of inline editing instead of opening a separate Edit Screen for the lines of the invoice since their invoices include a lot of line items and it is easier for them to enter data in an excel-like way.

Regards,
George

So, in case of inline editing, you have possibility to add either DataGrid#addEditorPreCommitListener or DataGrid#addEditorPostCommitListener to update value of the edited entity according to the other fields.

Unfortunately, for now, there is no ability to update Inline Editor fields during editing, but this feature will be introduced in the CUBA Platform 6.7 release. See the issue.

Regards,
Gleb