Conditional Calculation of Values from Different Fields Based on Flag

A customer had a problem with their Commercial Invoice template. The Net Weight Total wasn’t calculating correctly. The total should be based on two different fields, depending on a flag that tells which field to use. Even though they created a “var tagging element” for “net-weight” (following our guide to calculate the running total, the total still isn’t showing the correct weight values from the right invoice lines.

Data Structure and Analysis:

Here is an example of the data structure:

Based on the flag in the last column, called Match, we need to decide which field to use. If the flag is set to TRUE, we will use the Net Weight field. If the flag is set to FALSE, we will use the LoadLineWeight column.

Solution

While the approach the customer used based on our manual should work, I’d like to present a simpler solution using a summary field tagging element.

The first step is to add a new summary field tagging element anywhere in the document where you’d like the calculation to be displayed, and link it to the collection of data where the fields are located. In my case, this will be the SalesInvoiceLines.

Once this is done, there’s just one more step. We need to create the XPath expression that will determine which value to use for the calculation (i.e. to aggregate), and apply it within the Aggregate property under the SummaryField properties.

In my case, the XPath expression will look like this:

iif(@Match = "true", @NetWeight, @LoadLineWeight)

This expression checks in each line from the SalesInvoiceLines collection if the Match field is true. If it is, it will use the NetWeight field for calculating the Sum. If it’s not true, it will use the LoadLineWeight field instead.

Once this is set up, you’ll get the correct calculation based on the flag and which field to use. As you can see, it’s quite simple to implement, and you can set it up quickly.