[]
        
(Showing Draft Content)

Calculated Fields

Calculated fields are new columns created by the CollectionView and placed inside of a FlexGrid control that uses custom expressions to populate their cells.

Creating the CollectionView

We'll first need to get the data that will populate the CollectionView. In most cases, this will be a call to a database, but here we'll use sample data:

export function getData() {
    return [
        { product: ‘Banana’, brand: ‘Chiquita’, unitPrice: 45.95, qty: 12, discount: .08 },  
        { product: ‘Apple’, brand: ‘Granndy’, unitPrice: 65.95, qty: 23, discount: 0.02 },  
        ...,  
    ]
}

Then, we'll pass this data off to the CollectionView:

export function getCalculatedView() {
    return new CollectionView(getData() { ... });
}

Implementing Custom Expressions

The calculatedFields property can now be used to create custom expressions that our FlexGrid control can use to create the Calculated Fields columns:

export function getCalculatedView() {
    return new CollectionView(getData() {
        calculatedFields: {
            fullName: ($) => [$.brand, $.product].join(' '),
            allCaps: ($) => $.fullName.toUpperCase(),  
            totalPrice: ($) => ($.unitPrice * $.qty) * (1 - $.discount),  
            tax: ($) => $.totalPrice * 0.12 
        }
    });
}

Assigning the CollectionView to FlexGrid

The CollectionView now needs to be assigned as the itemsSource for our FlexGrid. However, we can now use our calculatedFields that we created as bindings for new columns in the grid:

new FlexGrid(‘#theGrid’, {
    alternatingRowStep: 0,  
    showMarquee: true,  
    selectionMode: ‘MultiRange’,  
    autoGenerateColumns: false,  
    columns: [  
        // regular data fields  
        { binding: ‘product’, header: ‘Product’ },  
        { binding: ‘brand’, header: ‘Brand’ },  
        { binding: ‘unitPrice’, header: ‘Unit Price’, format: ‘c’ },  
        { binding: ‘qty’, header: ‘Quantity’, format: ‘n0’ },  
        { binding: ‘discount’, header: ‘Discount’, format: ‘p0’ },  
        // calculated fields  
        { binding: ‘fullName’, header: ‘Full Name’, cssClass: ‘calculated’ },  
        { binding: ‘allCaps’ header: ‘UpperCase’ cssClass: ‘calculated’ },  
        { binding: ‘totalPrice’, header: ‘Total Price’, format: ‘c’ cssClass: ‘calculated’ },  
        { binding: ‘tax’, header: ‘Tax Amount’, format: ‘c’, cssClass: ‘calculated’ },  
    ],  
    itemsSource: getCalculatedView()  
});

We'll also add some CSS to differentiate the calculatedFields from the regular data fields:

.calculated {
    background-color: azure;
}

Wijmo Calculated Fields FlexGrid