TL;DR: Struggling to customize JavaScript pivot table values beyond defaults? This guide shows how Syncfusion® aggregateCellInfo event lets you adjust specific numbers, display strings in pivot tables, and handle custom subtotal calculations for precise data insights.
As a developer, you’ve likely wrestled with rigid data displays in your apps, those moments when default pivot table values just don’t cut it for real-world analysis. What if you could easily customize JavaScript pivot table values to show exactly what your users need? Enter Syncfusion® powerful JavaScript Pivot Table control, where the aggregateCellInfo event becomes your secret weapon for tailored data visualizations.
The pivot table is one of the most powerful tools in data analysis, perfect for summarizing large datasets. Syncfusion® JavaScript Pivot Table control stands out by letting you go beyond defaults, whether tweaking numeric values, displaying strings in pivot tables, or handling custom subtotal calculations. In this comprehensive guide, we’ll explore various techniques to customize your Syncfusion® JavaScript Pivot Table.
How to customize JavaScript Pivot Table specific values?
Imagine analyzing sales data for different regions across different years and encountering a specific number that needs manual adjustment due to updated real-world information. Customizing that specific value ensures accuracy in your data representation and can be pivotal for making informed decisions.
Utilizing the aggregateCellInfo event
The aggregateCellInfo event is triggered when a cell in the pivot table is being rendered. This event allows users to customize the values of the cells before they are displayed in the user interface.
Here’s the step-by-step approach to customizing a specific value:
Step 1: Identify the value to customize
First, determine the exact criteria of the value you wish to customize. In our scenario, the specific data point we want to change is in the Sold field located in the France row under the FY 2015 column.
Step 2: Implement the aggregateCellInfo event
Use the aggregateCellInfo event to target the value that meets your specified criteria. Here’s the sample code snippet you’ll need:
var pivotObj = new ej.pivotview.PivotView({
aggregateCellInfo: function (args) {
if (args.row.valueSort.levelName ==='France' && args.column.valueSort.levelName ==='FY 2015' && args.fieldName === 'Sold') {
args.value = 222; // Customize the value as needed
}
},
});
Why this approach?
This technique affords a great deal of flexibility by allowing you to modify data dynamically during runtime without altering the underlying data source. It keeps your main dataset intact and provides a way to represent conditional data changes.
Displaying strings in Pivot Table: Overriding default value
Understanding default aggregation
When dealing with string values in a pivot table, the native behavior of Syncfusion® JavaScript Pivot Table doesn’t display the actual strings within the value cells. Instead, it counts the occurrences of each string since a pivot table generally expects to handle numerical aggregation.
Overriding default aggregation
To show string values in their original form, use the aggregateCellInfo event to bypass the default counting behavior:
How to implement
Displaying string data in a Pivot Table
First, identify the field in your dataset that contains the string data you wish to display. For example, to show employee details such as Designation, Mail Id, or Location, you can place these fields on the value axis. This ensures detailed information is displayed directly without unnecessary categorical separation, enhancing readability and simplifying the table structure. Next, utilize the aggregateCellInfo event to modify the values and display string data directly.
Customizing headers for clarity
When no fields are assigned to the “columns” axis, the default column headers in the pivot table typically display grand totals in a format such as Total + Aggregation type + of+ value field caption (e.g., Total Sum of Designation ). This format can be misleading when displaying non-aggregated string data. To address this, use the headerCellInfo event to remove redundant phrases such as Total and the aggregation type, ensuring the headers are concise and relevant.
var pivotObj = new ej.pivotview.PivotView({
dataSourceSettings: {
dataSource: getPivotData(),
expandAll: false,
columns: [],
values: [{ name: 'Designation' }, { name: 'Mail', caption:'Mail Id' }, { name: 'Location' }],
rows: [{ name: 'EmployeeName' }],
showGrandTotals: false,
},
aggregateCellInfo: function (args) {
// Triggers for every value cell; you can get the value cells by their field name.
if (args.cellSets[0] != null) {
// Assign its unique string data values here.
args.value = args.cellSets[0][args.fieldName];
}
},
gridSettings: {
headerCellInfo: function(args) {
// Customize the value header text of the pivot table to remove the aggregation type and the word "Total."
args.node.querySelector('.e-headertext').innerText = args.cell.column.headerText
}
}
});
pivotObj.appendTo('#PivotTable');
Benefits
This customization provides clarity and insight, especially when the unique string data is critical to analysis, enhancing the value of your reports.
Similarly, sometimes, you need to see the original, unaltered piece of data rather than aggregated data within the pivot table. For example, if you need to validate the data or need individual data entries for analytical purposes, accessing non-aggregated data can be beneficial.
Customizing subtotal calculations in a Pivot Table
Why customize a subtotal calculation?
In data reporting, subtotals, such as a sum or average, typically provide an aggregate view. However, there are situations where these default calculations do not meet specific analytical needs. For example, your data may require a custom algorithm to better represent the underlying trends or insights.
For example, consider a dataset showing sales figures by country and quarter. If you want to calculate a subtotal for France in Q1 using multiplication instead of summation, customization is necessary.
The approach
To implement this customization, we will use the aggregateCellInfo event. This event allows us to intercept the subtotal calculation and apply custom logic.
Implementation steps
- Initialize a variable: Start with a variable to compute your custom subtotal value. For multiplication purposes, initialize it to 1.
-
Event logic:
- Verify if the current cell matches the criteria (e.g., belongs to France in FY 2015 and is a Q1 column).
- Check if the row is a child member. If so, multiply its sales value by the running product stored in your variable.
- Finally, check if the row is at the subtotal level and, if so, replace the default subtotal value with your calculated result.
- Reset your variable: After assigning the value, reset your variable for the next calculation.
var value = 1;
var pivotObj = new ej.pivotview.PivotView({
dataSourceSettings: {
columns: [{ name: 'Quarter' }],
subTotalsPosition: 'Bottom',
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Year' }, { name: 'Country' }, { name: 'Products' }]
},
aggregateCellInfo: function (args) {
// Verify that the current cell has a row header labeled 'France' under "FY 2015,"
// a column header labeled "Q1," and a value field labeled "Sold."
if (
args.row.valueSort.levelName.includes('FY 2015.France') &&
args.fieldName === 'Sold' &&
args.column.actualText === 'Q1'
) {
// Check if the row belongs to the child by using the level
if (args.row.level === 2) {
// Multiply the value of each child member
value *= args.value;
}
// Determine if the current cell is part of the row subtotal by checking its level
if (args.row.level === 1) {
if (value !== 1) {
// Assign the calculated value
args.value = value;
value = 1;
}
}
}
}
});
Best practices
Set subTotalsPosition to Bottom: This is crucial because the calculations for individual child rows are completed first, before calculating the totals for parent rows. By processing child rows first, you ensure that your custom calculations have the correct data for calculating the subtotals. If the subtotals were positioned at the top, you might attempt to calculate them before all the necessary data is available, resulting in incorrect totals.
GitHub reference
For more details, refer to the GitHub demo.
Conclusion
Syncfusion® JavaScript Pivot Table offers flexible and powerful options for customizing how data is presented, whether altering specific numeric values, displaying unique strings, showing non-aggregated data, or customizing subtotal values. By leveraging the aggregateCellInfo event, you can ensure that your data visualizations are accurate and tailored to meet your specific insights requirements.
These customization techniques enhance your ability to extract meaningful insights from your data, empowering better strategic decisions. Feel free to explore these methods further to maximize the potential of your Syncfusion® JavaScript Pivot Table.
If you’re already a Syncfusion® user, you can download the latest version of Essential Studio® from the license and downloads page. New to Syncfusion® Start your journey with a 30-day free trial and explore over 1,900 UI components, including powerful charting tools for Blazor.
If you need assistance, please do not hesitate to contact us via our support forum, support portal, or feedback portal. We are always eager to help you!
Resources
- Getting started in EJ2 JavaScript Pivotview control
- Aggregation in EJ2 JavaScript Pivotview control
- How to display values in Pivot Table with custom formatting depending on their headers?
- How to show value and percentage difference between current and previous year in JavaScript Pivot Table?
Related Blogs
- How to Deploy Syncfusion Spreadsheet Docker Image with ASP.NET Core 8.0
- Host Open and Save Services for JavaScript Spreadsheet with ASP.NET Core and Docker
- Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List
- Optimize Performance: Choose the Best Data Source for Pivot Table
This article was originally published at Syncfusion.com.
Top comments (0)