Introduction When working with Syncfusion’s React Pivot Table, you may want to customize the sorting behavior so that clicking on a pivot button cycles through multiple states: ascending, descending, and unsorted (None). By default, the Pivot Table only allows toggling between ascending and descending sorting orders. However, if you need to implement a custom sorting cycle, this article will guide you through the steps to achieve it using the actionBegin event. To achieve a sorting cycle that toggles between ascending, descending, and unsorted (None) states, you can override the default sorting behavior by using the actionBegin event. This event allows you to customize the sorting logic before it is applied. Here is the implementation for customizing the sorting cycle in a Pivot Table: [index.js] import { PivotViewComponent, GroupingBar, FieldList, Inject } from '@syncfusion/ej2-react-pivotview'; let pivotObj; function Default() { return ( <div className="control-pane"> <div className="control-section"> <PivotViewComponent id="PivotView" ref={d => pivotObj = d} enableValueSorting={true} showGroupingBar={true} showFieldList={true} actionBegin={actionBegin.bind(this)} > </PivotViewComponent> </div> </div> ); function actionBegin(args) { if (args.actionName == 'Sort field') { args.cancel = true; // Cancel the default sorting action to implement custom logic let previousOrder; let currentOrder; // Check if there are existing sort settings if (args.dataSourceSettings.sortSettings.length > 0) { for (var i = 0; i < args.dataSourceSettings.sortSettings.length; i++) { // Find the previous sort order for the field being sorted if (args.dataSourceSettings.sortSettings[i].name == args.fieldInfo.fieldName) { previousOrder = args.dataSourceSettings.sortSettings[i].order; break; } else { previousOrder = 'Ascending'; // Default to ascending if not found } } } else { previousOrder = 'Ascending'; // Default sort order when no settings exist } // Determine the next sort order based on the previous order currentOrder = previousOrder === 'Ascending' ? 'Descending' : previousOrder === 'Descending' ? 'None' : 'Ascending'; // Update sort settings for the specified field if (args.dataSourceSettings.sortSettings.length > 0) { for (var i = 0; i < args.dataSourceSettings.sortSettings.length; i++) { if (args.dataSourceSettings.sortSettings[i].name == args.fieldInfo.fieldName) { // Update existing field's sort order pivotObj.dataSourceSettings.sortSettings[i].order = currentOrder; } else { // Add new field sort setting if not already present pivotObj.dataSourceSettings.sortSettings.push({ name: args.fieldInfo.fieldName, order: currentOrder }); } } } else { // Add sort setting if no previous settings exist pivotObj.dataSourceSettings.sortSettings.push({ name: args.fieldInfo.fieldName, order: currentOrder }); } pivotObj.refreshData(); // Refresh the Pivot Table to apply the new sorting } } } export default Default; The following GIF images illustrate the difference before and after implementing the above workaround solution, GIF Before custom sorting cycle: After custom sorting cycle: For a practical demonstration, refer to the sample of stackblitz Conclusion I hope you enjoyed learning how to customize header sorting behavior in React Pivot Table. You can refer to our React Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction When working with JavaScript Pivot Table, there may be scenarios where you need to apply custom styles to grand total cells. This customization can significantly enhance the readability and aesthetic appeal of the pivot table. It can be achieved by adding custom styles to your stylesheet and subsequently using the headerCellInfo and queryCellInfo events to effectively apply these styles to both row and column grand total cells. Below is a step-by-step guide on how to do this, along with a code example. Step 1: Define custom styles First, you need to define the custom style within your stylesheet that you want to apply to the row and column grand total cells. In the following code example, we initialize a couple of CSS classes named row_grandtotal and column_grandtotal to specify the styles for row and column grand total cells, respectively. [index.css] .row_grandtotal { background-color: thistle !important; font-family: cursive !important; } .column_grandtotal { background-color: skyblue !important; font-family: 'Franklin Gothic Medium' !important; } You can adapt the code to meet your specific requirements, such as applying a different background color or specifying a different font family for the row and column grand totals cells. NOTE When customizing the styles, the !important rule is used to ensure that these custom styles have higher specificity than the default styles applied by the library. This ensures your customizations take effect. Step 2: Apply custom styles using events Next, you need to use the headerCellInfo and queryCellInfo events to apply custom styles to the grand total cells. The headerCellInfo event is triggered while rendering each column header cell in a pivot table, allowing you to apply custom styles to the column grand total headers. On the other hand, the queryCellInfo event is triggered during the rendering of each row and value cell in the pivot table, providing the opportunity to customize the current cell, such as adding or removing styles. Below is a code snippet that demonstrates how to utilize these events: [index.js] var pivotObj = new ej.pivotview.PivotView({ gridSettings: { headerCellInfo: (args) => { // Apply custom styles for column grand total headers. if(args.node.classList.contains("e-gtot")) { args.node.classList.add("column_grandtotal"); } }, queryCellInfo: function(args){ // Retrieve the current cell information. var colIndex = Number(args.cell.getAttribute('data-colindex')); // Check if the cell belongs to the row grand total. if ((args.data[colIndex].rowHeaders == "" && args.data[colIndex].columnHeaders !== "") || (args.data[colIndex].axis == 'row' && args.data[colIndex].actualText == 'Grand Total')) { args.cell.classList.add("row_grandtotal"); } // Check if the cell belongs to the column grand total. else if (args.data[colIndex].columnHeaders == "") { args.cell.classList.add("column_grandtotal"); } } }, }); Here’s a breakdown of how the code works: Within the headerCellInfo event, we check whether the current cell belongs to the column grand total header by using the e-gtot class. If it does, we add the column_grandtotal class to apply custom styles to this cell. Similarly, within the queryCellInfo event, we determine whether the current cell represents the row grand total, column grand total, or neither. For row grand total cells, we check if the rowHeaders property is an empty string while the columnHeaders property is not empty, or if the cell’s axis is designated as “row” and the actualtext property is “Grand Total”. When this condition is met, we include the row_grandtotal class in the cell. This action effectively applies custom styles to the row grand total cells. For column grand total cells, we check if the columnHeaders property is an empty string. If this condition is met, we add the “column_grandtotal” class to the cell, thereby applying custom styles to it. The following screenshot portrays the results of the code snippet mentioned above. Screenshots For a practical example of this code in action, you can refer to the following sample of stackblitz. Conclusion By following the steps outlined in this article and using the provided code example, you can easily apply custom styles to the grand total cells in a JavaScript Pivot Table. You can also refer to our JavaScript Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction Saving and loading the React Pivot Table report allows you to preserve the current state of the component and reload it into the pivot table as required. By default, this functionality is accessible through the built-in toolbar options. For more details, please refer to the user guide documentation. However, In some cases, you may want to programmatically save and load a report using external buttons. This article demonstrates how to implement this customization seamlessly. Save and load the report using external buttons To achieve the desired customization, you must add two external buttons. One button is used to save the current layout of the pivot table to local storage, while the other button is used to load the saved layout back into the pivot table. Below is an example of a code snippet that demonstrates how to accomplish this using the Syncfusion Button component: [index.js] import { PivotViewComponent } from '@syncfusion/ej2-react-pivotview'; import { ButtonComponent } from '@syncfusion/ej2-react-buttons'; // Here, we define a variable to access the instance of the pivot table let pivotObj; let obj; function Default() { function StoreData() { // Create a unique identifier obj = 'PivotTable' + pivotObj.element.id; // Store current pivot table state to local storage localStorage[obj] = pivotObj.getPersistData(); } function load() { // Check if there's saved data in local storage for this pivot table if (localStorage[obj]) { // Load the modified data from the local storage in the pivot table here. pivotObj.loadPersistData(localStorage[obj]); } } return ( <div id="btn-control" style={{ marginBottom: '5px' }}> <ButtonComponent id="save-btn" className='e-info' style={{ marginRight: '5px' }} onClick={StoreData}>Save</ButtonComponent> <ButtonComponent id="load-btn" className='e-info' onClick={load}>Load</ButtonComponent> </div> <PivotViewComponent id='PivotView' ref={d => pivotObj = d} > </PivotViewComponent> ); } export default Default; Explanation of the code snippet: When the “Save” button is clicked, the StoreData event method is triggered. Within the event method, we generate a unique identifier by concatenating ‘PivotTable’ with the component’s ID (i.e., pivotObj.element.id). This identifier ensures that the saved state remains unique in local storage. Afterwards, we extract the current state of the pivot table using the pivotObj.getPersistData() method and store it in the local storage under the generated key. Similarly, when the “Load” button is clicked, the load event method is triggered. Within the event method, we check if there is any saved data in the local storage for the specific pivot table using the unique key. If the data exists, we utilize the pivotObj.loadPersistData() method to reload it back onto the pivot table. This action effectively restores the saved state of the pivot table. The following GIF image portrays the results of the code snippet mentioned above. GIF For a practical demonstration, refer to the sample of stackblitz. Additional resources To save and load a report as a JSON file, please refer to the UG documentation. To save and load reports to a SQL database, please refer to the UG documentation. Conclusion By following the steps outlined in this article and using the provided code examples, you can easily save and load the React Pivot Table report using external buttons. You can refer to our React Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction In JavaScript Pivot Table, you can group the date field into different sections, such as years, quarters, months, and days. Each section appears as a button on the grouping bar. Each button typically includes icons for sorting, filtering, and a cancel option. However, there might be scenarios in which you want to selectively hide the sort icon for specific date grouping fields, such as the months field. This approach can enhance the user experience by customizing the user interface according to specific requirements. This article explains how to selectively hide the sort icon for a specific date grouping field in the JavaScript Pivot Table grouping bar. Hiding the sorting icon for a specific date grouping field To achieve the desired customization, you will need to use the enginePopulated event of the pivot table. This event is triggered after the pivot engine has been populated, allowing you to customize UI elements such as sort icons for the specific date grouping field. Below is an example of a code snippet that demonstrates how to achieve this: [index.js] var pivotObj = new ej.pivotview.PivotView({ dataSourceSettings: { enableSorting: true, rows: [{ name: 'Date', caption: 'Date' }], groupSettings: [ { name: 'Date', type: 'Date', groupInterval: ['Years', 'Months', 'Days'], }, ] }, showGroupingBar: true, enginePopulated: function (args) { // Iterate through all rows in the data source settings for(var i=0; i<pivotObj.dataSourceSettings.rows.length; i++){ // Check if the current row is the 'months' grouping of the date field if (pivotObj.dataSourceSettings.rows[i].name == 'Date_date_group_months') { // Disables the sort icon for this specific field pivotObj.dataSourceSettings.rows[i].showSortIcon = false; } } }, }); In the code example above, within the enginePopulated event, we iterate through each row field defined in the dataSourceSettings. During the iteration, we check if the current row corresponds to the grouping of months by utilizing the pivotObj.dataSourceSettings.rows[i].name property. Each date grouping follows a specific naming convention: ‘Base field name + _ + “date_group” + _ + group type’. For instance, if there is a date field named ‘Date’ and it is grouped by months, the field name would be ‘Date_date_group_months’. This naming convention helps us easily identify specific fields that are grouped by month. If the field name matches, we set the showSortIcon property for that field to false, which effectively conceals the sorting icon for the month grouping field. The following screenshots portray the difference between before and after implementing the above workaround solution: Screenshots Before implementing the workaround solution, After implementing the workaround solution, For a practical example of this code in action, you can refer to the following sample of stackblitz. Additional resources: To hide the sort icon on non-date grouping fields, refer to the UG documentation. Conclusion By following the steps outlined in this article and using the provided code example, you can easily hide the sorting icon for a specific date grouping field in the grouping bar of a JavaScript Pivot Table. You can also refer to our JavaScript Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction When working with Angular Pivot Table, there may be occasions where you require the flexibility to export drill-through data into different file formats, such as PDF, Excel, and CSV. This can be essential for further data analysis or record-keeping purposes. This article explains how you can seamlessly export drill-through data into the aforementioned file formats. Exporting the drill-through data In order to export drill-through data, you will need to use the beginDrillThrough event of the pivot table. This event is triggered just before the drill-through dialog appears. By default, the drill-through data is displayed using the Syncfusion Grid Component. By handling this event, you can access the instance of the Grid component and invoke the appropriate export methods. Below is an example of a code snippet that demonstrates how to achieve this: [app.component.html] <ejs-pivotview #pivotview id='PivotView' allowDrillThrough="true" (beginDrillThrough)="beginDrillThrough($event)"> </ejs-pivotview> [app.component.ts] import { PivotView, DrillThroughService, BeginDrillThroughEventArgs, } from '@syncfusion/ej2-pivotview'; import { Grid, Toolbar } from '@syncfusion/ej2-angular-grids'; import { ClickEventArgs } from '@syncfusion/ej2-navigations'; @Component({ selector: 'app-root', templateUrl: 'app.component.html', providers: [FieldListService, DrillThroughService], }) export class AppComponent { @ViewChild('pivotview') public pivotObj?: PivotView; beginDrillThrough(args: BeginDrillThroughEventArgs) { if (args.gridObj) { Grid.Inject(Toolbar); // Injecting the Toolbar module into the Grid component let gridObj: Grid = args.gridObj; gridObj.toolbar = ['ExcelExport', 'CsvExport', 'PdfExport']; // Adding export options to the toolbar. gridObj.allowExcelExport = true, // Enabling Excel and CSV export. gridObj.allowPdfExport = true, // Enabling PDF export export. (gridObj.toolbarClick = (args: ClickEventArgs) => { switch(args.item.id) { case this.pivotObj.element.id + '_drillthroughgrid_pdfexport': gridObj.pdfExport(); // Here, we export the drill-through grid as a PDF file format. break; case this.pivotObj.element.id + '_drillthroughgrid_excelexport': gridObj.excelExport(); // Here, we export the drill-through grid in Excel file format. break; case this.pivotObj.element.id + '_drillthroughgrid_csvexport': gridObj.csvExport(); // Here, we export the drill-through grid in CSV file format. break; } }); } } Explanation of the code snippet: First, we inject the Toolbar module into the Grid component. This module is essential for adding toolbar items that will be used for the exporting process. Then, we define a variable named gridObj to access the instance of the Grid component. Following this, we configure toolbar items for exporting by using the gridObj.toolbar property. This action allows you to select the desired export format directly from the UI. Afterwards, we enabled the PDF, Excel, and CSV exports by setting gridObj.allowExcelExport and gridObj.allowPdfExport to true, respectively. As a final step, we use the gridObj.toolbarClick event. This event is triggered whenever a toolbar item is clicked. Within this event, we check the ID of the clicked toolbar item. If the ID corresponds with either PDF, Excel, or CSV exports, we invoke the respective gridObj.pdfExport(), gridObj.excelExport(), or gridObj.csvExport() method. Each of these methods is designed to export the drill-through data in the chosen file format. The following screenshot portrays the results of the code snippet mentioned above. screenshots Toolbar Items were added to the drill-through grid, PDF Export, Excel Export, CSV Export, For a practical demonstration, please refer to the sample of stackblitz. Conclusion By following the steps outlined in this article and using the provided code examples, you can effectively implement the functionality to export the drill-through data to PDF, Excel, and CSV formats. You can refer to our Angular Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Angular Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction: By default, when you double-click on any value cell in a pivot table, the drill-through dialog appears and displays detailed raw data based on the fields configured in the report settings. This default behavior may not be suitable for all use cases, especially when you want to display only the row field, column field, and value field information pertaining to the selected value cell. This approach simplifies the user interface by removing unnecessary fields. This article demonstrates how to implement functionality by customizing the default behavior of the React Pivot Table drill-through dialog. Displaying only the selected cell value information in the drill-through dialog: To achieve the desired customization, you will need to use the beginDrillThrough event of the pivot table. This event is triggered before the drill-through dialog is rendered, providing an opportunity to modify its contents according to your specific requirements. Below is a code example that illustrates how to display only the row field, column field, and value field information based on the selected value cell: [index.js] import { PivotViewComponent, DrillThrough, Inject } from '@syncfusion/ej2-react-pivotview'; function DrillThroughComponent() { let pivotObj; function beginDrillThrough(args) { // Initialize variables to store the row header and column text of the clicked cell. let rowHeader; let columnHeader; // Determine if the selected cell belongs to a child member within the row if (args.cellInfo.currentCell.rowHeaders.includes(pivotObj.dataSourceSettings.valueSortSettings.headerDelimiter)) { // Extract the proper row header text using the header delimiter and update "rowHeader" let childRow = args.cellInfo.currentCell.rowHeaders.split(pivotObj.dataSourceSettings.valueSortSettings.headerDelimiter); rowHeader = childRow[childRow.length - 1]; } else { // Directly assign the row header text if clicked cell is belongs to parent row. rowHeader = args.cellInfo.currentCell.rowHeaders; } // Here we extract the column header name if (args.cellInfo.currentCell.columnHeaders.includes(pivotObj.dataSourceSettings.valueSortSettings.headerDelimiter)) { let childColumn = args.cellInfo.currentCell.columnHeaders.split(pivotObj.dataSourceSettings.valueSortSettings.headerDelimiter); columnHeader = childColumn[childColumn.length - 1]; } else { columnHeader = args.cellInfo.currentCell.columnHeaders; } // Obtain the raw data to find the field name of the row and column let rawData = Object.values(args.cellInfo.rawData[0]); var rowFieldName; var columnFieldName // Get the row field name based on the raw data for (var k = 0; k < rawData.length; k++) { if (rawData[k] == rowHeader) { rowFieldName = Object.keys(args.cellInfo.rawData[0])[k]; } else if(rawData[k] == columnHeader) { columnFieldName = Object.keys(args.cellInfo.rawData[0])[k] } } // Iterate through the grid columns to only show the information of the row field, column field and value field of the chosen cell by concealing all other fields (columns). for (var i = 0; i < args.gridObj.columns.length; i++) { if (args.gridObj.columns[i].field !== rowFieldName && args.gridObj.columns[i].field !== args.cellInfo.currentCell.actualText && args.gridObj.columns[i].field !== columnFieldName) { // Hide all other fields (columns) in the drill-through dialog args.gridObj.columns[i].visible = false; } } } return ( <PivotViewComponent id='PivotView' ref={(scope) => { pivotObj = scope; }} allowDrillThrough={true} beginDrillThrough={beginDrillThrough}> <Inject services={[DrillThrough]}/> </PivotViewComponent>); } export default DrillThroughComponent; Explanation of the code snippet: First, we initialize a couple of variable’s named rowHeader and columnHeader within the beginDrillThrough event to hold the text of the row and column headers corresponding to the clicked value cell. Following this, we check whether the selected cell’s row headers contain the pivot table’s header delimiter. This check helps determine whether the cell belongs to a child member within the row. If it does, we extract the appropriate row header text from the args.cellInfo.currentCell.rowHeaders property and assign it to the rowHeader variable. Otherwise, we directly assign the value to the rowHeader. We derive the column header by following a similar approach. Afterward, we retrieve the first set of raw data from the pivot table using the args.cellInfo.rawData[0] property and loop through it to identify the field names for both the row and column, based on the values found in the rowHeader and columnHeader, respectively. Finally, we iterate through all the columns in the drill-through grid. If a column’s field does not match the previously identified row field name (i.e., rowFieldName), the column field name (i.e., columnFieldName), or the actual text of the selected value cell (which represents the value field), we set the args.gridObj.columns[i].visible property to false. This action effectively displays the row field, column field, and value field information pertaining to the selected value cell by concealing all other columns. The following screenshots portray the difference between before and after implementing the above workaround solution: screenshots: Selected value cell in the pivot table, Before implementing the workaround solution, After implementing the workaround solution, For a practical demonstration, refer to the sample of stackblitz. Conclusion: By following the steps outlined above, you can easily show the row field, column field, and value field information in the drill-through dialog according to the value cell selected in the React Pivot Table. You can refer to our React Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction In certain scenarios, you might want to limit the export options available in the pivot table toolbar export menu to ensure that users can only export data in specific file formats. For instance, you may want to enable exporting exclusively for the PDF file format while concealing other options such as CSV and Excel. This approach simplifies the user interface by removing unnecessary options. This article will guide you through the process of hiding specific export options, such as CSV and Excel from the export menu in the Angular Pivot Table toolbar. Hide specific export options from the menu To achieve the desired customization, you will need to use the dataBound event of the pivot table. This event is triggered when the pivot table is rendered, providing the opportunity to access the export menu instance from the DOM and apply a condition to hide certain export format options. Here is an example code snippet demonstrating how to accomplish this: [app.component.html] <ejs-pivotview #pivotview id='PivotView' [dataSourceSettings]=dataSourceSettings allowExcelExport='true' allowPdfExport='true' showToolbar='true' [toolbar]='toolbarOptions' (dataBound)='dataBound($event)'> </ejs-pivotview> [app.component.ts] import { PivotView } from '@syncfusion/ej2-pivotview'; export class AppComponent { public pivotObj: PivotView; public toolbarOptions: ToolbarItems[]; @ViewChild('pivotview') public pivotObj: PivotView; dataBound(args: any) { let pivotID= this.pivotObj.element.id; let exportMenu = select('#' + pivotID + 'export_menu', this.pivotObj.element).ej2_instances[0]; exportMenu.beforeItemRender = function (args: any) { if (args.element.id == pivotID + "csv" || args.element.id == pivotID + "excel") { args.element.style.display = "none"; } } } ngOnInit(): void { this.toolbarOptions = ['Export'] as ToolbarItems[]; } Explanation of the code snippet: First, we obtain the ID of the Pivot Table instance. This ID is then utilized to select the export menu instance from the DOM. Following this, we invoke the select() method with the ID of the pivot table concatenated with _export_menu to precisely target the export menu. Afterwards, we call the beforeItemRender() event of the export menu and apply a condition to check the id of each menu item. If the id corresponds with any of the specified formats (i.e.,CSV or Excel), we set the args.element.style.display property to none. This action effectively conceals the option within the export menu. You can adapt the code to meet your specific requirements, such as hiding various toolbar menu options, like sub-total, grand total, and more. The following screenshots portray the difference between before and after implementing the above workaround solution: screenshots Before implementing the workaround solution, After implementing the workaround solution, For a practical demonstration, please refer to the sample of stackblitz. Conclusion By following the steps outlined in this article and using the provided code examples, you can easily hide specific export options from the export menu in the Angular Pivot Table toolbar. You can refer to our Angular Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Angular Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction: When working with Vue Pivot Table, there may be instances where you require the flexibility to select specific rows in a pivot table through an external button, rather than directly interacting with the pivot table itself. This approach enhances user interaction by providing a more accessible way to dynamically select specific rows in a pivot table. This guide will demonstrate how to select rows in a Vue Pivot Table based on their header text upon clicking an external button. Moreover, it will show how to select both rows and their associated child members using the same external button interaction. Add an external button: First, you need to create a button that will be used to select rows in the pivot table. To maintain a consistent UI, you can use the Syncfusion Button component. Here is an example code snippet demonstrating how to accomplish this: [App.vue] <template> <ejs-button id="btn" v-on:click="selectRow" isPrimary='true'>Select rows</ejs-button> <ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"> </ejs-pivotview> </template> <script lang="ts"> import { PivotViewComponent } from "@syncfusion/ej2-vue-pivotview"; import { ButtonComponent } from "@syncfusion/ej2-vue-buttons"; export default { components: { 'ejs-pivotview': PivotViewComponent, 'ejs-button': ButtonComponent }, } </script> Selecting specific rows in a pivot table based on header text: After configuring the button, you must implement the logic to select specific rows in the pivot table upon clicking the button. This involves adding a method within your script section that will be executed upon the button click. Here is a code snippet that demonstrates how to select specific rows in a pivot table based on the header text: [App.vue] <script lang="ts"> export default { data: () => { return { gridSettings: { allowSelection: true, selectionSettings: { mode: "Row", type: "Multiple", } }, }; }, methods: { selectRows: function(args: any) { // Obtaining a reference to the Pivot Table instance. let pivotObj = ((this as any).$refs.pivotview).ej2Instances; // Here, we initialize a variable to determine the specific row index. let rowIndex = -1; // Array to strore selected row index let selectedRows = []; // Iterate through the pivotValues property of the Pivot Table instance for (var i = 0; i < pivotObj.pivotValues.length; i++) { for (var j = 0; pivotObj.pivotValues[i] != null && j < pivotObj.pivotValues[i].length; j++) { if (pivotObj.pivotValues[i][j] && pivotObj.pivotValues[i][j].axis === 'row') { // Here we increment the row index variable if the axis of the current cell is 'row'. rowIndex++ if (pivotObj.pivotValues[i][j].valueSort && pivotObj.pivotValues[i][j].valueSort.levelName.includes('Road Bikes')) { // Here we push the `rowIndex` to `selectedRows` array selectedRows.push(rowIndex); }; } } } // Select the specific row based on the rowIndex pivotObj.grid.selectionModule.selectRows(selectedRows); }, } } </script> Here’s a breakdown of how the code works: First, we define a variable named pivotObj within the selectRow() method to access the instance of the pivot table. We use this variable to identify the specific row indices and then select the corresponding rows. Following this, we initialize a variable named rowIndex to track the current row index as we iterate over the pivot table data. Additionally, we create an array called selectedRows to store the indices of the selected rows. Afterward, we iterate over pivotObj.pivotValues to access the details of each cell within the pivot table. Throughout this iteration, we use the args.cellInfo.valueSort.levelName property to determine whether the row header text includes the specified criteria (in this case, “Road Bikes”). The index of each matching row is then added to the selectedRows array. Once the row indices are determined, we invoke the pivotObj.grid.selectionModule.selectRows method to select the corresponding rows in the pivot table based on the indices in the selectedRows array. You can adapt the code to fit your specific requirements, such as selecting different rows in the pivot table. NOTE It is important to note that row indices start at 0, indicating that the first row has an index of 0. The following GIF image portrays the results of the code snippet mentioned above: GIF For a practical demonstration, please refer to the sample of stackblitz. Selecting specific row and its associated child members: In certain scenarios, you might want to select specific rows and their associated child members in a pivot table using an external button click. The approach is similar to selecting rows by header text, but this time, we focus on the parent header text (i.e., ‘France’). Here is an example code snippet demonstrating how to accomplish this: <script lang="ts"> export default { methods: { selectRows: function(args: any) { // Obtaining a reference to the Pivot Table instance. let pivotObj = ((this as any).$refs.pivotview).ej2Instances; // Here, we initialize a variable to determine the specific row index. let rowIndex = -1; // Array to store selected row indices let selectedRows = []; // Iterate through the pivotValues property of the Pivot Table instance for (var i = 0; i < pivotObj.pivotValues.length; i++) { for (var j = 0; pivotObj.pivotValues[i] != null && j < pivotObj.pivotValues[i].length; j++) { if (pivotObj.pivotValues[i][j] && pivotObj.pivotValues[i][j].axis === 'row') { // Here we increment the row index variable if the axis of the current cell is 'row'. rowIndex++ if (pivotObj.pivotValues[i][j].valueSort && pivotObj.pivotValues[i][j].valueSort.levelName.includes('France')) { // Here we push the `rowIndex` to `selectedRows` array selectedRows.push(rowIndex); }; } } } // Select the specific rows based on the rowIndex pivotObj.grid.selectionModule.selectRows(selectedRows); }, } } </script> The following GIF image portrays the results of the code snippet mentioned above: GIF For a practical demonstration, please refer to the sample of stackblitz. Conclusion By following the steps outlined above, you can easily add the functionality to select specific rows in a Vue Pivot Table via an external button. You can also refer to our Vue Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Vue Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction Conditional formatting allows you to highlight cells in a React Pivot Table based on certain conditions. However, there might be scenarios where you need to exclude subtotal values from these conditional formatting rules. By default, you can prevent conditional formatting from being applied to grand total values by setting the applyGrandTotals property to false. However, there is no direct property for excluding subtotal values. This article guides you through a custom approach to prevent conditional formatting from being applied to subtotal values. Restrict conditional formatting from being applied to subtotal values In order to restrict conditional formatting from being applied to subtotal values, you need to use the queryCellInfo event in your code. This event is triggered during the rendering of each row and value cells in the pivot table, providing the opportunity to customize the current cell, such as adding or removing styles, editing the value, etc. By handling this event, you can precisely target the subtotal values and restrict conditional formatting from being applied to them. Below is an example code snippet that demonstrates how to achieve this: [index.js] import { PivotViewComponent, Inject, ConditionalFormatting } from '@syncfusion/ej2-react-pivotview'; let dataSourceSettings = { conditionalFormatSettings: [ { value1: 0, conditions: 'GreaterThan', style: { backgroundColor: '#f48fb1', color: 'black', fontFamily: 'Tahoma', fontSize: '12px' } } ], }; function ConditionalFormattingClass() { function queryCellInfo(args) { let colIndex = Number(args.cell.getAttribute('data-colindex')); // Checking if the current cell is a subtotal cell. if (args.data[colIndex].axis == 'value' && args.data[colIndex].actualText != "" && args.data[colIndex].isSum && !args.data[colIndex].isGrandSum) { // Iterate through cell classes to identify and remove conditional formatting classes for(var i=0; i<args.cell.classList.length; i++) { if(args.cell.classList.contains("format" + pivotObj.element.id + i)) { // Removing the conditional formatting class args.cell.classList.remove("format" + pivotObj.element.id + i); } } } } return ( <PivotViewComponent id='PivotView' ref={(pivotview) => { pivotObj = pivotview; }} dataSourceSettings={dataSourceSettings} allowConditionalFormatting={true} gridSettings={{ queryCellInfo: queryCellInfo }}> <Inject services={[ConditionalFormatting]}/> </PivotViewComponent>); } export default ConditionalFormattingClass; In the above code snippet, we check whether the current cell belongs to the subtotal by using properties of the cell data, such as axis, actualText, isSum, and isGrandSum. This effectively filters out the subtotal cells from the rest. Following this, we iterate through the class list of the cell and check whether any of the class names correspond to the pattern for conditional formatting classes ("format" + pivotObj.element.id + i). Once the appropriate conditional formatting class was identified, we removed the specified class from the cell element. This will effectively restrict conditional formatting from being applied to subtotal values. The following screenshots portray the difference between before and after implementing the above workaround solution: Screenshots Before implementing the workaround solution, After implementing the workaround solution, For a practical demonstration, please refer to the sample of stackblitz. Additional references: For more details on the conditional formatting feature, please refer to the official Syncfusion documentation. Conclusion By following the steps outlined in this article and using the provided code example, you can easily restrict conditional formatting from being applied to subtotals in a React Pivot Table. You can refer to our React Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction Synchronizing two pivot tables with a single field list can significantly enhance the user experience by maintaining consistent data across both pivot tables. This approach ensures that any action, such as adding, removing, sorting, and filtering fields in the field list of the first pivot table, is automatically reflected in the second pivot table. This article will guide you on how to synchronize field list actions between two identical JavaScript Pivot Tables. Synchronizing two identical pivot tables with a single field list To achieve synchronization, you must use the enginePopulating event. This event is triggered after the pivot engine has been populated, and it allows you to synchronize the dataSourceSettings of both pivot tables. As a result, any changes made in the first pivot table will be instantly reflected in the second pivot table. Below is a JavaScript code snippet that demonstrates this approach: [index.ts] var pivotObj1 = new ej.pivotview.PivotView({ enginePopulating: function(args) { // Synchronize dataSourceSettings with the second Pivot Table pivotObj2.dataSourceSettings = pivotObj1.dataSourceSettings; // Refresh the second Pivot Table to reflect the changes pivotObj2.refreshData(); }, }); In the code example above, within the enginePopulating event, we update the dataSourceSettings of the second pivot table (i.e., pivotObj2) to match the current dataSourceSettings of the first pivot table (i.e., pivotObj1). After updating the settings, we invoke the refreshData() method on pivotObj2 to programmatically refresh the second pivot table, thereby displaying the pivot table according to the updated dataSourceSettings. The following GIF image portrays the results of the code snippet mentioned above: GIF For a practical demonstration, please refer to the sample of stackblitz. Conclusion By following the steps outlined in this article and using the provided code example, you can easily synchronize two identical JavaScript Pivot Tables with a single field list. You can also refer to our JavaScript Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction When working with Angular Pivot Table, there may be occasions where you wish to open the chart type settings dialog using an external button rather than relying on the built-in toolbar options. This approach enhances user interaction by providing a more accessible way to dynamically change the chart type and choose from multiple axis modes, such as “Single”, “Stacked”, or “Combined”, according to your preferences. This article outlines the steps to open the chart type settings dialog programmatically via an external button. Step 1: Add an external button First, incorporate an external button within your HTML file, typically named app.component.html. This button will be used to trigger the opening of the chart type settings dialog. Here is a code sample that demonstrates how to add a button using the Syncfusion Button component: [app.component.html] <button ejs-button #chartType id="ChartType" (click)="onChange()" [isPrimary]="true">Chart Type Settings Dialog</button> <ejs-pivotview #pivotview id='PivotView' [displayOption]=displayOption [showToolbar]='true' [toolbar]='toolbarOptions'> </ejs-pivotview> Step 2: Opening the chart type settings dialog After setting up the button, you need to implement the logic to open the chart type settings dialog when the button is clicked. This involves adding a method in your TypeScript file (i.e., app.component.ts) that will be executed upon the button click. [app.component.ts] import { PivotViewModule, DisplayOption, ToolbarService, ToolbarItems, PivotView } from '@syncfusion/ej2-angular-pivotview'; @Component({ selector: 'app-root', styleUrls: ['app.component.css'], providers: [ToolbarService], templateUrl: 'app.component.html', standalone: true, imports: [PivotViewModule, ButtonModule] }) export class AppComponent { public displayOption: DisplayOption; public toolbarOptions!: ToolbarItems[]; @ViewChild('pivotview') public pivotView: PivotView; onChange() { (this.pivotView.toolbarModule as any).createChartTypeDialog(); } ngOnInit(): void { this.toolbarOptions = ['Chart'] as ToolbarItems[]; this.displayOption = { view: 'Chart' } as DisplayOption; } } In the code example above, within the onChange() method, we invoke the this.pivotView.toolbarModule.createChartTypeDialog() method to effectively open the chart type settings dialog. The following GIF image portrays the results of the code snippet mentioned above: GIF For a practical demonstration, please refer to the sample of stackblitz. Conclusion By following the steps outlined in this guide, you can easily open the chart type settings dialog in an Angular Pivot Table via an external button. You can refer to our Angular Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Angular Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction By default, field members (aka headers) are sorted based on ASCII values in an Angular Pivot Table. This means that when sorting is applied in ascending order, capital letters (A-Z) are sorted before lowercase letters (a-z), and vice versa for descending order. This default behavior might not be suitable for all use cases, especially when you prefer case-insensitive sorting. This article demonstrates how to implement this functionality by overriding the default ASCII value-based sorting in the pivot table. Sorting in a case-insensitive manner through the onHeadersSort event. To achieve case-insensitive sorting, you can utilize the onHeaderSort event of the pivot table. This event is triggered before the sorting is performed, allowing you to customize the default sorting behavior based on your requirements. Below is an example that demonstrates how to achieve case-insensitive sorting: [app.component.html] <ejs-pivotview #pivotview id='PivotView' (onHeadersSort)="onHeaderSort($event)" showGroupingBar='true' showFieldList='true' > </ejs-pivotview> [app.component.ts] import { PivotView } from '@syncfusion/ej2-pivotview'; export class AppComponent { public pivotObj: PivotView; @ViewChild('pivotview') public pivotObj: PivotView; onHeaderSort(args: any) { var customSortedMembers; if(args.sortOrder == "Ascending") { // Case-insensitive sorting for the specified field in ascending order. customSortedMembers = args.members.slice().sort(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }); } else if(args.sortOrder == "Descending") { // Case-insensitive sorting for the specified field in descending order. customSortedMembers = args.members.slice().sort(function (b, a) { return a.toLowerCase().localeCompare(b.toLowerCase()); }); } else if(args.sortOrder == "None") { // Retains the original order (useful when resetting the sort order). customSortedMembers = args.members; } // Assign the custom sorted members back to the args object. args.members = customSortedMembers; // Set IsOrderChanged to true to apply the custom sort order. args.IsOrderChanged = true; } Here’s a breakdown of how the code works: First, within the onHeaderSort, we check the current sort order by using the args.sortOrder property. If the sorting order is set to ascending, we create a shallow copy of the args.members array by using JavaScript’s slice() method to prevent modifying the original dataset. Following this, we perform case-insensitive sorting for the specified field using the sort method. Inside this method, we convert all the member names to lowercase using the toLowerCase() method and then compare them using the localeCompare() method. This approach ensures that the field members are sorted in ascending order without considering case sensitivity. If the sorting order is set to descending, a similar process is carried out but in reverse order to achieve a descending sort. When the sortOrder is None, the original order of members is retained without any changes. Finally, the sorted members are assigned back to args.members, and args.IsOrderChanged is set to true to indicate that the order has been customized. This action ensures that the pivot table is displayed in the customized sorting order. The following screenshots portray the difference between before and after implementing the above workaround solution: screenshots Before implementing the workaround solution, After implementing the workaround solution, For a practical demonstration, refer to the sample of stackblitz. Conclusion By overriding the default ASCII value-based sorting behavior with a custom case-insensitive sorting logic, you can achieve a more intuitive sorting order in an Angular Pivot Table. You can refer to our Angular Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Angular Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction When working with a JavaScript Pivot Table, there may be occasions where you need to customize the dimensions of the filter dialog to enhance the user interface or to improve data presentation. This can be accomplished by overriding the default styles applied to these elements. This article provide guidance on adjusting the width and height of the filter dialog in a pivot table. Customizing the width and height of the filter dialog In order to alter the width and height of the filter dialog, you must target the CSS class associated with the dialog. This is feasible by writing custom CSS styles that override the defaults. Below is an example code snippet that demonstrates how to achieve this. [index.css] .e-pivotview .e-member-editor-dialog, /* Target the filter dialog when accessing it through the grouping bar UI */ .e-pivotfieldlist-container .e-member-editor-dialog, /* Target the filter dialog when accessing it through the field list UI */ .e-pivotview .e-member-editor-dialog .e-member-editor-container-outer-div, /* Target the member's container inside the filter dialog */ .e-pivotfieldlist-container .e-member-editor-dialog .e-member-editor-container-outer-div { max-height: unset !important; /* Unsets any max-height to allow custom height */ max-width: unset !important; /* Unsets any max-width to allow custom width */ } /* Customizing width and height for the filter dialog accessed through the grouping bar UI */ .e-pivotview .e-member-editor-dialog { width: 100% !important; /* Set width to 100% of the viewport */ height: 100% !important; /* Set height to 100% of the viewport */ } /* Customizing width and height for the filter dialog accessed through the field list UI */ .e-pivotfieldlist-container .e-member-editor-dialog { width: 100% !important; /* Set width to 100% of the viewport */ height: 100% !important; /* Set height to 100% of the viewport */ } First, we target the CSS selectors .e-member-editor-dialog and .e-member-editor-container-outer-div classes within both the .e-pivotview and the .e-pivotfieldlist-container in order to remove any restrictions on the maximum height and width of the filter dialog. This can be accomplished by setting the max-width and max-height to unset. Following this, we utilize the CSS selectors .e-pivotview .e-member-editor-dialog and .e-pivotfieldlist-container .e-member-editor-dialog to specify the width and height of the filter dialog as 100% when it is accessed through either the grouping bar or the field list UI. NOTE The dimensions of the filter dialog are adjusted based on the size of its parent element. This means that the size of the dialog will change to fit either the pivot table container when accessed through the grouping bar UI or the pivot table field list container when accessed through the field list UI. When customizing the styles, the !important rule is used to ensure that these custom styles have higher specificity than the default styles applied by the library. This ensures your customizations take effect. The following screenshot portrays the results of the code snippet mentioned above. Screenshot Customized filter dialog size when accessed through the grouping bar UI: Customized filter dialog size when accessed through the field list UI: For a practical example of this code in action, you can refer to the following sample of stackblitz. Conclusion By following the steps outlined in this article and using the provided code example, you can easily customize the width and height of the filter dialog in a JavaScript Pivot Table. You can also refer to our JavaScript Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction When working with JavaScript Pivot Table, there might be scenarios where you need to customize the name displayed for field members (i.e., headers) within the member filter dialog. This customization significantly enhances readability and provides a more intuitive way to present data. This article demonstrates how to achieve this customization seamlessly. Preliminary step: Customize header text in pivot table Before diving into the customization, it’s necessary to first customize the header text in the pivot table. This step is essential to maintain consistency and prevent incorrect or misleading information from being displayed in the pivot table UI. For guidance on customizing the header text, please refer to the following knowledge base article. Customizing field member name in member filter dialog After ensuring the header text is properly customized, you can proceed to customize the field member name within the member filter dialog using the memberEditorOpen event. This event is triggered before the member filter dialog opens, providing an opportunity to modify the name of each member based on your requirements. Below is a code snippet that demonstrates how to accomplish this customization: [index.js] var pivotObj = new ej.pivotview.PivotView({ showFieldList: true, showGroupingBar: true, memberEditorOpen(args: any) { // Check if the current field is "Year" if(args.fieldName == "Year") { // Iterate over all members of the "Year" field for(var i=0; i<args.fieldMembers.length; i++) { // Customizing member names based on specific conditions if(args.fieldMembers[i].name == "FY 2015") { // Customizing the name to "2015" args.fieldMembers[i].name = args.fieldMembers[i].name.split(" ")[1]; } } } } }); In the example above, within the memberEditorOpen event, we check whether the field name is “Year”. If so, we iterate through all the members of the field within the member filter dialog. If a member name matches “FY 2015”, it is renamed to “2015”. This customization is achieved by splitting the member’s name by a space (" ") and selecting the item at the second index (i.e., 1) to be the new name. You can add more conditions to rename other members as needed. The following screenshot portrays the results of the code snippet mentioned above. Screenshot For a practical example of this code in action, you can refer to the following sample of stackblitz. Conclusion By following the steps outlined in this article and using the provided code example, you can easily customize the field member name within the member filter dialog of a JavaScript Pivot Table. You can also refer to our JavaScript Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction When working with React Pivot Table, there may be scenarios where you initially need to display columns pertaining to the current year and its quarter. This feature enhances the user experience by immediately showcasing relevant time-based data. The following code snippet demonstrates how to implement this functionality by identifying the column index corresponding to the current year and quarter and then programmatically adjusting the horizontal scroll position accordingly. Identify the column index for the current year and its quarter In order to obtain the column index, you need to use the headerCellInfo event in your code. This event is triggered during the rendering of each column header cell in a pivot table and enables you to find the index of a specific column. Below is a code example that demonstrates how to identify the column index that represents the current year and its quarter. [index.js] import { PivotViewComponent } from '@syncfusion/ej2-react-pivotview'; let count = 0; // Tracks the column index position of the current year and quarter. let isInitial = true; // A flag to ensure scroll position is set only during the initial render. let currentYearFlag = false; // Used to stop counting once the current year and quarter column is found. // Get the current date const currentDate = new Date(); // Get the current year from the current date const currentYear = currentDate.getFullYear(); // Get the current month (0-indexed, so January is 0 and December is 11) const currentMonth = currentDate.getMonth(); // Calculate the current quarter const currentQuarter = Math.floor(currentMonth / 3) + 1; let currentYearWithQuarter = currentYear + "-Q" + currentQuarter; function Default() { let pivotObj; function headerCellInfo(args){ // Here, get the column index of the current year and quarter. if(pivotObj && !currentYearFlag && args.node.innerText !== "") { count++; // Once we obtained the column position of the current year, we stopped increasing the count variable. if(args.node.innerText == currentYearWithQuarter){ currentYearFlag = true; } } } return ( <PivotViewComponent id='PivotView' ref={(scope) => { pivotObj = scope; }} gridSettings={{ columnWidth: 140, headerCellInfo: headerCellInfo }}> </PivotViewComponent>); } export default Default; Here’s a breakdown of how the code works: First, we initialize two variables named “count” and “currentYearFlag”. The ‘count’ variable is used to track the column index for the current year and its quarter as we iterate through header cells in a pivot table. Meanwhile, “currentYearFlag” is a boolean variable that stops the ‘count’ variable from increasing once the current year and its quarter are identified. Following this, we obtain the current date, extract the current year and month, and then calculate the quarter based on the current month. Afterward, we create a string representation “currentYearFlag” that combines the current year and the quarter in the format Year-Quarter. Then, within the headerCellInfo event, we check if the pivot object exists, if the flag (i.e., “currentYearFlag”) for identifying the current year and quarter remains false, and if the cell’s inner text is not empty. If these conditions are met, we increment the “count” to keep track of the column index. Finally, we check whether the text within each header cell (args.node.innerText) matches the “currentYearWithQuarter” variable. If there is a match, the “currentYearFlag” is set to true. This signifies that the column representing the current year and quarter has been identified and that the “count” will not increase for subsequent columns. Adjust the horizontal scroll position of the Pivot Table After identifying the column index for the current year and its quarter, you need to use the dataBound event in your code. This event is triggered when the pivot table is either rendered or refreshed. It allows you to adjust the horizontal scrolling position of the pivot table to initially show the columns related to the current year and its quarter. [index.js] import { PivotViewComponent } from '@syncfusion/ej2-react-pivotview'; let isInitial = true; // A flag to ensure scroll position is set only during the initial render. function Default() { let pivotObj; function dataBound() { if (pivotObj && pivotObj.element.querySelector('.e-content') && isInitial && pivotObj.element.offsetHeight > 200) { isInitial = false; var scrollBar = pivotObj.element.querySelector('.e-content'); // Here we calculate required scroll width var width = pivotObj.gridSettings.columnWidth * ((count-1)* pivotObj.dataSourceSettings.values.length); scrollBar.scrollLeft = width; } } return ( <PivotViewComponent id='PivotView' ref={(scope) => { pivotObj = scope; }} gridSettings={{ columnWidth: 140,headerCellInfo: headerCellInfo }} dataBound={dataBound}> </PivotViewComponent>); } export default Default; Here’s a breakdown of how the code works: First, we initialize a boolean variable “isInitial” to ensure that the scrolling action is executed only once during the initial rendering process. Then, within the dataBound event, we check if the pivotObj object exists and its content is correctly loaded. Additionally, we verify if the pivot table height exceeds a certain limit (i.e., 200px). Once the conditions are met, the “isInitial” flag is set to false to prevent this code from running multiple times unnecessarily. Following this, we calculate the required scroll width to bring the current year and quarter column into view. This can be achieved by multiplying the column width (i.e., pivotObj.gridSettings.columnWidth) by the total number of columns up to the target, which can be calculated as (count-1) * pivotObj.dataSourceSettings.values.length. Finally, the calculated width is assigned to the scroll left property of the scrollbar (i.e., scrollBar.scrollLeft). This process automatically scrolls the content of the pivot table horizontally, thereby displaying the columns for the current year and its corresponding quarter (i.e., 2024-Q1). The following screenshots images portray the difference between before and after implementing the above workaround solution: Screenshots Before implementing the workaround solution, After implementing the workaround solution, For a practical example of this code in action, you can refer to the following sample of stackblitz. Conclusion I hope you enjoyed learning how to position the columns in a React Pivot Table according to the current year and its quarter. You can refer to our React Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction When working with the React Pivot Table, there might be scenarios where you need to limit the number of fields that can be selected in the pivot table field list. This ensures a cleaner data representation and prevents the pivot table from becoming overloaded with too many fields. This article demonstrates how to disable unselected fields in the pivot table field list once the count of selected fields reaches or exceeds a maximum limit (i.e., 4). Additionally, we will show you how to limit the minimum number of field selections in the field list, specifically ensuring that at least one field remains selected for the row, column, and value axes. Restrict the maximum number of field selections in the pivot table field list To implement this functionality, you need to use the dataBound event in the pivot table. This event is triggered when the pivot table is rendered, and it allows you to apply modifications such as enabling or disabling field list items based on certain conditions. Below is an example of how to restrict the field selection when the number of selected fields reaches or exceeds a specific limit, which is 4 in this case: [index.js] import { PivotViewComponent, Inject, FieldList } from '@syncfusion/ej2-react-pivotview'; function PivotFieldList() { let pivotObj; function dataBound(){ var unSelectedFields = []; // variable to store unselected fields var selectedFields = []; // variable to store unselected fields let fields = pivotObj.pivotFieldListModule.treeViewModule.fieldTable.treeData; for (var i = 0; i < fields.length; i++) { // Here, we store the fields that were not selected in the array. if (!fields[i].isSelected) { unSelectedFields.push(fields[i].id); } else { // Here, we store the selected fields in an array. selectedFields.push(fields[i].id); } } if (selectedFields.length >= 4) { // Disable the unselected fields if the user selected field is greater than 4 pivotObj.pivotFieldListModule.treeViewModule.fieldTable.disableNodes(unSelectedFields); } } return ( <PivotViewComponent id='PivotView' ref={(scope) => { pivotObj = scope; }} showFieldList={true} dataBound={dataBound}> <Inject services={[FieldList]}/> </PivotViewComponent>); } export default PivotFieldList; Explanation of the code snippet: First, within the dataBound, we initialized two arrays, unSelectedFields and selectedFields, to keep track of the IDs (i.e., field names) of fields that are unselected and selected, respectively. Then, we iterate through all the fields available in the field list UI. For each field, we check if it is selected. If a field is not selected, it will be added to the unSelectedFields array. Conversely, if a field is selected, it will be added to the selectedFields array. After processing all fields, we check whether the selectedFields array has four or more elements (indicating that four or more fields have been selected). If the condition is met, we invoke the method pivotObj.pivotFieldListModule.treeViewModule.fieldTable.disableNodes and pass the unSelectedFields array as an argument. This method disables the fields identified by the provided IDs, thereby preventing users from selecting more than the allowed number of fields. The following GIF image, which portrays the results of the code snippet mentioned above, GIF For a practical example of this code in action, you can refer to the following sample in stackblitz. Enforcing minimum field selection in field list In certain scenarios, you might want to enforce a minimum number of field selections for different axes (such as rows, columns, and values) in the field list to ensure the data representation remains meaningful and to prevent displaying an empty pivot table. This functionality can be achieved by handling the fieldDrop event. This event is triggered before a field drops into any axis, allowing you to impose a minimum field selection rule on the specified axes. Here is a code example that demonstrates how to maintain at least one field in the row, column, and value axes [index.js] import { PivotViewComponent, Inject, FieldList } from '@syncfusion/ej2-react-pivotview'; function PivotFieldList() { function fieldRemove(args) { // Here, we check the axis of the currently removed field if(args.axis !== 'filters' && args.dataSourceSettings[args.axis].length - 1 === 0) { // Displaying an alert message when user attempts to remove the last field in any of the axes. alert('At least one field must be selected for the row, column, and value axes'); // Preventing the field removal action by setting 'cancel' property to true. args.cancel = true; } } return (<PivotViewComponent id='PivotView' ref={(scope) => { pivotObj = scope; }} showFieldList={true} dataBound={dataBound} fieldRemove={fieldRemove.bind(this)}> <Inject services={[FieldList]}/> </PivotViewComponent>); } export default PivotFieldList; First, we ensure that the axis of the currently removed field isn’t ‘filters’. This is because the requirement only applies to the row, column, and value axes. Following this, we verify whether the removal of the current field would result in an empty axis. If the conditions mentioned above are met, we display an alert message to inform the user that at least one field must remain selected for the non-filter axes. Afterward, we prevent the removal of the selected field by setting the args.cancel property to true. The following GIF image, which portrays the results of the code snippet mentioned above, GIF For a practical example of this code in action, you can refer to the following sample in stackblitz. Conclusion: I hope you enjoyed learning how to limit the number of field selections in the React Pivot Table field list. You can refer to our React Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction Rendering additional UI components, like a progress bar, into a pivot table can significantly enhance data visualization by providing visual insights. This article will guide you on how to display the grand total values as progress bars in the JavaScript Pivot Table. Steps to insert a progress bar in the pivot table Step 1: Create the HTML element First, you need to define an HTML element that will be used to insert the progress bar into the grand total cells. This can be achieved by using the cellTemplate property. The property is triggered during the rendering of each cell in the pivot table and enables you to add a custom HTML element to the cells. Here is an example of how to define an HTML element by using the cellTemplate property: [index.js] window.getCellContent = function (e) { var template; if (e && e.targetCell.className.indexOf('e-valuescontent') > -1 && e.cellInfo.isGrandSum && e.cellInfo.columnHeaders === "" && (e.cellInfo.rowHeaders === "" || e.cellInfo.rowHeaders !== "")) { // Insert a DOM element into the grand total column cells here. template = '<div id="ProgressBar"></div>'; } else { template = ''; } return template; }; var pivotObj = new ej.pivotview.PivotView({ cellTemplate: '${getCellContent(data)}', }); In the above code example, we checked if the current cell belongs to the value cell by utilizing the e.valuescontent CSS selector. Following this, we verified whether the cell is a grand total cell using the e.cellInfo.isGrandSum property and the e.cellInfo.columnHeaders CSS selector. If a cell meets all these conditions, we create a custom HTML element (in this case, a div with an id as ‘ProgressBar’). This element can be further customized to include a progress bar element within the pivot table. For other cells, the template remains an empty string, indicating that no DOM element should be added. Step 2: Insert the progress bar into the DOM element After creating the required HTML element, you will need to use the queryCellInfo event within the gridSettings. This event is triggered for each cell in the pivot table, allowing for the rendering of the progress bar within the previously created HTML element (i.e., ProgressBar). Here is an example of how to insert the progress bar within the created DOM element: [index.js] var pivotObj = new ej.pivotview.PivotView({ gridSettings: { columnWidth: 140, queryCellInfo: function(args) { var colIndex = Number(args.cell.getAttribute('data-colindex')); if (args.data[colIndex] && args.data[colIndex].axis == 'value' && args.data[colIndex].isGrandSum) { // Here, we retrieve the previously inserted DOM element var progressBar = args.cell.querySelector('#ProgressBar'); if(progressBar) { // Here, we remove the cell value args.cell.querySelector('.e-cellvalue').textContent = ""; // Here, we calculate the progress bar width based on the cell value var width = args.data[colIndex].value/100 progressBar.innerHTML = width < 100 ? width + '%' : '100%'; // Adjust the progress bar width based on calculated value progressBar.style.width = width < 100 ? width + '%' : '100%'; // Here, we set the height of the progress bar progressBar.style.height = '13px'; // Here, we apply padding for aesthetics look progressBar.style.padding = '10px'; // Here, we apply the background color for the progress bar based on the percentage value progressBar.style.background = width > 45 ? '#00b300' : '#df2222'; // Here, we set the text align progressBar.style.textAlign = 'left'; // Here, we apply the font color for text progressBar.style.color = 'White'; // Here, we apply the font size for text progressBar.style.fontSize = '11px'; } } } } }); Here’s a breakdown of how the code works: Within the queryCellInfo event, we use the isGrandSum property to check whether the current cell belongs to the grand total. If it does, we retrieve the previously created HTML element by targeting the ProgressBar id. Following this, we clear the current cell value by setting the .e-cellvalue element’s text content to an empty string. Afterwards, the progress bar’s width is calculated based on the cell value relative to a predetermined total value, in this case 100. If the calculated width is less than 100, we assign it to the progress bar; otherwise, we set the progress bar width to 100%. Finally, we set the height of the progress bar to 13px and the padding to 10px. Furthermore, the background color is set to green if the calculated width exceeds 45%; otherwise, it’s set to red. Additionally, we aligned the text to the left, changed the font color to white, and set the font size to 11 pixels. The following screenshot portrays the results of the code snippet mentioned above. Screenshot For a practical demonstration, refer to the sample of stackblitz. Conclusion I hope you enjoyed learning how to display grand totals as progress bars in the JavaScript Pivot Table. You can also refer to our JavaScript Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction When working with React Pivot Table, there might be scenarios where you need to customize the font styles, including font size, font family, and font style across different elements of the pivot table like the row headers, column headers, and value cells. This customization can significantly enhance the readability and aesthetic appeal of the pivot table. This article will guide you on how to achieve this customization using CSS. Customizing font styles To customize the font styles of the row headers, value cells, and column headers in a pivot table, you need to target these elements specifically using their respective CSS classes. The example below illustrates how to set the font-size, font-family, and font-style properties for the mentioned pivot table elements. [index.css] .e-pivotview .e-rowsheader .e-cellvalue, /* target the rows headers */ .e-pivotview .e-headercell .e-cellvalue, /* target the columns headers */ .e-pivotview .e-headertext, /* target the values header */ .e-pivotview .e-grid .e-rowcell { /* target the values cells */ font-size: 18px !important; /* Setting the font size */ font-family: sans-serif !important; /* Setting the font family */ font-style: italic !important; /* Setting the font style */ } Here’s a breakdown of how the code works: Row headers customization: The row headers in the pivot table have been customized with specific font styles by targeting the CSS selector .e-pivotview .e-rowsheader .e-cellvalue. Column headers customization: To customize the font styles for column headers in the pivot table, we are targeting the CSS selector .e-pivotview .e-headercell .e-cellvalue. Value headers customization: Customization of the value headers in the pivot table is achieved through the use of the CSS selector .e-pivotview .e-headertext. Value cell customization: By targeting the CSS selector .e-pivotview .e-grid .e-rowcell, customization is achieved for the value cells in the pivot table. Finally, each of these elements is assigned a font-size of 18 pixels, a sans-serif font-family, and an italic font-style. NOTE When customizing the styles, the !important rule is used to ensure that these custom styles have higher specificity than the default styles applied by the library. This ensures your customizations take effect. The following screenshots portray the difference between before and after customizing font styles, Before customization After customization For a practical demonstration, refer to the sample of stackblitz. Additional references Apply custom styles to the pivot table headers Customize the style of the pivot table header, value, and summary cells. Conclusion By customizing the CSS properties as shown in the example, you can effectively change the font styles for the entire contents of a React Pivot Table, including row headers, value cells, and column headers. You can refer to our React Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction When working with React Pivot Table, there might be scenarios where you need to customize the dimensions of the drill-through dialog and the grid column contained within it for a better user interface or to improve the data presentation. This can be achieved by overriding the default styles applied to these elements. This article will provide guidance on adjusting the width and height of the drill-through dialog and the grid column within it. Adjusting the width and height of the drill-through dialog In order to alter the width and height of the drill-through dialog, you must target the CSS class associated with the dialog. This is feasible by writing custom CSS styles that override the defaults. Below is an example code snippet that demonstrates how to achieve this. /* customize the drill through dialog width and height here. */ .e-drillthrough-dialog.e-control.e-dialog.e-lib.e-dlg-modal.e-popup.e-popup-open{ width: 100% !important; /* Custom width for the dialog */ max-height: unset !important; /* Unsets any max-height to allow custom height */ height: 100% !important; /* Custom height for the dialog */ } Customizing the drill-through grid column height After adjusting the dimensions of the dialog, you might want to customize the height of the grid column within the drill-through dialog to ensure it fits well within the newly sized dialog. This can also be achieved by overriding the corresponding CSS classes. The code snippet below provides an example of how to set a custom height for the drill-through grid column. /* customize the drill through grid column height here. */ .e-drillthrough-dialog .e-drillthrough-grid .e-gridcontent .e-content { height: 90vh !important; /* Custom height for the grid column */ } Note When customizing the styles, the !important rule is used to ensure that these custom styles have higher specificity than the default styles applied by the library. This ensures your customizations take effect. It’s a good practice to adjust the drill-through grid content height to be less than the dialog height to accommodate other elements of the dialog, such as the header and padding, as shown in the example above. It’s essential to specify the grid column height in viewport units (i.e., vh) rather than percentages to ensure that a vertical scrollbar is displayed when the content exceeds the visible area. The following screenshots portray the difference between before and after adjusting the width and height of the drill-through dialog, Before customization After customization For a practical demonstration, refer to the sample of stackblitz. Conclusion I hope you enjoyed learning how to customize the width and height of the drill-through dialog in a React Pivot Table. You can refer to our React Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction In certain situations, you may want to provide additional interactivity by displaying a custom dialog box whenever a value cell is double-clicked in a pivot table. This can be useful for showing detailed information, conducting validations, or initiating other custom actions. This article will guide you on how to create a custom dialog in the Blazor Pivot Table when double-clicking on a value cell. Creating a custom dialog box upon double-clicking a value cell In order to create a custom dialog when double-clicking on a value cell in a pivot table, you can utilize the DrillThrough event. This event is triggered upon clicking a value cell in the pivot table and allows for the creation of a custom dialog box. The code example below demonstrates how to create a custom dialog by using the Syncfusion Blazor Dialog Component when double-clicking a value cell in a pivot table. Note: To use the DrillThrough event in the pivot table, you must set the AllowDrillThrough property to true within the SfPivotView class. [Index.razor] @using Syncfusion.Blazor.PivotView @using Syncfusion.Blazor.Popups <SfPivotView TValue="ProductDetails" ID='PivotView' @ref="pivot" Width="100%" AllowDrillThrough="true"> ... <PivotViewEvents TValue="ProductDetails" DrillThrough="drillThrough"></PivotViewEvents> </SfPivotView> @*Custom Dialog Component.*@ <SfDialog Target="#PivotView" @ref="Dialog" Width="300px" ShowCloseIcon="true" @bind-Visible="@Visibility"> <DialogTemplates> <Header> Dialog </Header> <Content> <p> This is a custom dialog, you can update your custom validation here. </p> </Content> </DialogTemplates> <DialogAnimationSettings Effect="@AnimationEffect"/> <DialogButtons> <DialogButton IsPrimary="true" Content="CANCEL" OnClick="@OnBtnClick" /> </DialogButtons> </SfDialog> @code { SfPivotView<ProductDetails> pivot; private SfDialog Dialog { get; set; } private bool Visibility { get; set; } = false; private DialogEffect AnimationEffect = DialogEffect.Zoom; // Close the dialog unsing the button. private async Task OnBtnClick() { await Dialog.HideAsync(); } private async Task drillThrough(DrillThroughEventArgs args) { // Restrict the existing dialog here. args.Cancel = true; // And display the custom dialog here. await Dialog.ShowAsync(); } } In the above code example, inside the DrillThrough event method, we prevented the default drill-through dialog box from appearing by setting the args.Cancel property to true. Following this, we have created a custom dialog box using the Syncfusion Blazor Dialog Component and its properties, for instance, its title, message, size, and animation appearance, among others. You can modify this event as per your requirements to customize the dialog box and its contents. The following GIF image, which portrays the results of the code snippet mentioned above, Sceenshot You can refer to this GitHub sample for a practical demonstration of this code. Conclusion I hope you enjoyed learning how to create a custom dialog in a Blazor Pivot Table when double-clicking on a value cell. You can also refer to our Blazor Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Blazor Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction In modern data visualization, rendering multi-series pivot charts offers a comprehensive view for comparing various data series over the same period or categories. This can be particularly useful when dealing with complex datasets, allowing for a more intuitive understanding of the data. This article will explain how you can render a multi-series pivot chart in the Blazor Pivot Table component. Rendering multi-series pivot chart In order to render a multi-series chart in a pivot table, you can use the ChartSeriesCreated event. This event is triggered when the pivot chart series are created, allowing you to customize the series according to your requirements. Below is a code example that demonstrates how to use this event to display multiple series as different types of charts. [Index.razor] <SfPivotView @ref="Pivot" TValue="RData" Height="500"> ... <PivotViewDisplayOption View=View.Chart></PivotViewDisplayOption> <PivotChartSettings> <PivotChartSeries Type=Syncfusion.Blazor.PivotView.ChartSeriesType.Column></PivotChartSeries> </PivotChartSettings> <PivotViewEvents TValue="RData" ChartSeriesCreated="chartSeries"></PivotViewEvents> </SfPivotView> @code { private void chartSeries(ChartSeriesCreatedEventArgs args) { for (var i = 0; i < args.Series.Count; i++) { if (args.Series[i].Name == "Solar" || args.Series[i].Name == "Wind") { // Here we have displayed "Solar" and "Wind" series as Line chart. args.Series[i].Type = Syncfusion.Blazor.Charts.ChartSeriesType.Line; } } } } In the above code snippet, we iterate through the args.Series array, which contains the chart series. We check the Name property of each series, and when it matches Solar or Wind, we change the series type to Line. This change will display the specified series as line charts in the pivot table. The following screenshot portrays the results of the code snippet mentioned above. Screenshot You can refer to this GitHub sample for a practical demonstration of this code. Conclusion I hope you enjoyed learning how to render a multi-series pivot chart in the Blazor Pivot Table component. You can also refer to our Blazor Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction In certain business scenarios, it may be essential to present data comparisons from different periods (for example, the current and previous year) in a pivot table. A clear presentation of such data comparisons enables decision-makers to identify insightful trends and patterns. This article demonstrates the process of creating calculated fields to display these differences and utilizes the AggregateCellInfo event for dynamic calculation within the Blazor Pivot Table. Create calculated fields In order to show the value and percentage differences between the current and previous year, you must create two calculated fields. The first field should represent the difference in value, while the other field will show the percentage difference. Below is a code sample that illustrates how you can accomplish this: [index.razor] <SfPivotView @ref="Pivot" TValue="ProductDetails" Height="500" AllowCalculatedField="true"> <PivotViewDataSourceSettings DataSource="@data"> <PivotViewColumns> <PivotViewColumn Name="Year"></PivotViewColumn> </PivotViewColumns> <PivotViewRows> <PivotViewRow Name="Country"></PivotViewRow> </PivotViewRows> <PivotViewValues> <PivotViewValue Name="Sold" Caption="Unit Sold"></PivotViewValue> <PivotViewValue Name="ValueDifference" Caption="ValueDifference"></PivotViewValue> <PivotViewValue Name="PercentageDifference" Caption="PercentageDifference"></PivotViewValue> </PivotViewValues> <PivotViewFormatSettings> <PivotViewFormatSetting Name="PercentageDifference" Format="P"></PivotViewFormatSetting> </PivotViewFormatSettings> <PivotViewCalculatedFieldSettings> <PivotViewCalculatedFieldSetting Name="ValueDifference" Formula="0"></PivotViewCalculatedFieldSetting> <PivotViewCalculatedFieldSetting Name="PercentageDifference" Formula="0"></PivotViewCalculatedFieldSetting> </PivotViewCalculatedFieldSettings> </PivotViewDataSourceSettings> </SfPivotView> Calculate the value and percentage difference between the current and previous year Once you have created the necessary calculated fields, you need to use the AggregateCellInfo event. This event is triggered during the rendering of each cell in the pivot table and allows you to compute both the actual value and the percentage differences between the current and previous years. Below is a code sample that illustrates how you can accomplish this: [Index.razor] <SfPivotView @ref="Pivot" TValue="ProductDetails"> <PivotViewEvents TValue="ProductDetails" AggregateCellInfo="AggregateCellInfo"></PivotViewEvents> </SfPivotView> @code { double? previousValue = 0; double? currentValue = 0; double? rowIndex = null; private void AggregateCellInfo(AggregateEventArgs args) { double changed; dynamic changedPercentage; // Here we get the current row index if (rowIndex == null) { rowIndex = args.Row.RowIndex; } else if (args.Row.RowIndex != rowIndex) { previousValue = 0; rowIndex = args.Row.RowIndex; } if (args.FieldName == "Sold") { if (previousValue == 0) { previousValue = args.Value; currentValue = null; } else { currentValue = args.Value; } } // Here we calculate the actual difference between current and previous year if (args.FieldName == "ValueDifference" && currentValue != null) { changed = (double)previousValue - (double)currentValue; args.Value = changed; } // Here we calculate the percentage difference between current and previous year else if (args.FieldName == "PercentageDifference" && currentValue != null) { changedPercentage = ((double)previousValue - (double)currentValue) / (double)currentValue; args.Value = changedPercentage; previousValue = currentValue; } // If the current value is null we set the cell as empty if (currentValue == null) { if (args.FieldName == "ValueDifference") { args.Value = null; } else if (args.FieldName == "PercentageDifference") { args.Value = null; args.AllowFormatting = false; } } } } Here’s a breakdown of how the code works: First, we define three variables: previousValue, currentValue, and rowIndex. The previousValue stores the value from the previous year, while currentValue holds the value for the current year. Meanwhile, rowIndex is used to store the current cell’s row index. Subsequently, within the AggregateCellInfo event, we check whether the current field name is “Sold”. If it is, we store the values of the previous and current years in the previousValue and currentValue variables, respectively. Following this, we check whether the current field name is “ValueDifference” and if the currentValue is not null. If both conditions are met, we calculate the actual value difference between previousValue and currentValue and assign it to the current cell value using the args.Value property. This action will accurately show the actual value difference between the years. Likewise, if the current field name is “PercentageDifference”, we calculate the percentage difference between previousValue and currentValue and assign it to the current cell value. This effectively displays the percentage difference between the years. If currentValue is null, implying that a comparison isn’t possible (for example, for the first data point where there isn’t any data from the previous year), both the “ValueDifference” and “PercentageDifference” field values are assigned null to show an empty cell. The following screenshot, which portrays the results of the code snippet mentioned above, Screenshot You can refer to this GitHub sample for a practical demonstration of this code. Conclusion I hope you enjoyed learning how to show value and percentage difference between current and previous year in a Blazor Pivot Table. You can also refer to our Blazor Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction The drill-through feature allows you to view the raw data of any JavaScript Pivot Table cell in a pop-up window by double-clicking on the cell. However, in scenarios where the column width cannot accommodate the full content, the data gets truncated due to space limitations. This is the actual behavior of the drill-through dialog in our Syncfusion Pivot Table. Although you can view the entire content of these truncated columns through the tooltip. This article demonstrates how to display a tooltip for truncated grid columns in the drill-through dialog. Display the tooltip for truncated gird columns in the drill-through dialog In order to display a tooltip for truncated grid columns, you need to use the beginDrillThrough event. This event is triggered before the drill-through dialog is rendered, which allows you to display a tooltip when hovering over the truncated grid columns. Here’s an example of how to display a tooltip for truncated grid columns in the drill-through dialog: [index.js] var pivotObj = new ej.pivotview.PivotView({ allowDrillThrough: true, beginDrillThrough: function (args) { for (var i = 0; i < args.gridObj.columns.length; i++) { // Here, we have enabled the tooltip for the truncated grid column. args.gridObj.columns[i].clipMode = 'EllipsisWithTooltip'; } }, }); In the preceding code snippet, we iterate through each column in the gridObj.columns property and set the clipMode property to EllipsisWithTooltip. This configuration allows us to view the entire content of the truncated columns without altering their width. The following screenshot, which portrays the results of the code snippet mentioned above, Screenshot For a practical example of this code in action, you can refer to the following Sample in Stackblitz. Conclusion I hope you enjoyed learning how to display a tooltip for truncated grid columns in the drill-through dialog of the JavaScript Pivot Table. You can also refer to our JavaScript Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction In certain scenarios, you may want to highlight specific rows in the Blazor Pivot Table to enhance readability and improve the presentation of data. This can be achieved by adding a custom style to your stylesheet and then using the CellTemplate property to apply this style to the rows you wish to highlight. Below is a step-by-step guide on how to do this, along with a code example. Adding custom style to your stylesheet First, you need to define the custom style that you want to apply to the rows. Here’s an example of how to define a custom style with a specific background color: [Index.razor] <style> .custom { background-color: #80cbc4 !important; } </style> The !important rule is used to ensure that this style overrides any other background color styles that might be applied to the cells in the row. Apply the style using the CellTemplate property Next, you need to use the CellTemplate property to apply the custom style to the specific row. This property is triggered during the rendering of each cell in the pivot table and allows you to add the custom CSS style to the cells of the row you want to highlight. Here’s a code example that demonstrates how to use the CellTemplate property to apply the custom style to a specific row: [Index.razor] <SfPivotView @ref="Pivot" TValue="ProductDetails" Height="500"> <PivotViewTemplates> <CellTemplate> @{ var data = (context as AxisSet); if (data != null) { // Here we have applied background color for "Road Bikes" row in "France" if ((data.ValueSort != null && data.ValueSort["levelName"].Equals("France.Road Bikes")) || (data.RowHeaders != null && data.RowHeaders.Equals("France.Road Bikes"))) { Pivot.PivotValues[data.RowIndex][data.ColIndex].CssClass = "custom"; @data.FormattedText } else { // Here, we displayed the original text if no condition is met. @data.FormattedText } } } </CellTemplate> </PivotViewTemplates> </SfPivotView> In the code example above, we access the data for the current cell through the context parameter within the CellTemplate property. Following this, the properties data.ValueSort["levelName"] and data.RowHeaders are used to identify the current row header name. If it matches the condition (in this case, France.Road Bikes), the custom style is applied to the cell using Pivot.PivotValues[data.RowIndex][data.ColIndex].CssClass property. This will change the background color of the specific row (in this case, the “Road Bikes” row under “France”). You can adapt the code to fit your specific requirements, such as checking for different row headers or applying different styles. The following screenshot, which portrays the results of the code snippet mentioned above, Screenshot You can refer to this GitHub sample for a practical demonstration of this code. Conclusion I hope you enjoyed learning how to highlight a specific row in a Blazor Pivot Table. You can also refer to our Blazor Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Blazor Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction By default, all headers in the pivot table can be expanded by setting the ExpandAll property to true. Similarly, all headers can be collapsed by setting the same property to false. However, in certain UI scenarios, you might want to either expand or collapse all headers at runtime. This article demonstrates how to dynamically expand and collapse all headers in a Blazor Pivot Table. Dynamically expanding or collapsing all headers To dynamically expand or collapse all headers in a pivot table, you need to add two external buttons. One button is used to expand all headers, while the other button is designated for collapsing all headers. Following this, you must handle the click events for these buttons in order to expand or collapse all the headers. Here’s a code sample demonstrating how to dynamically expand and collapse all headers in a pivot table using the Syncfusion Button component: [Index.razor] <SfButton CssClass="expand-button" IsPrimary="true" OnClick="@onExpand">Expand All</SfButton> <SfButton CssClass="collapse-button" IsPrimary="true" OnClick="@onCollapse">Collapse All</SfButton> <SfPivotView ID="PivotView" @ref="Pivot" TValue="ProductDetails"> <PivotViewDataSourceSettings ExpandAll="expandAll" DrilledMembers="drilledMembers"> </PivotViewDataSourceSettings> </SfPivotView> @code { private bool expandAll { get; set; } = false; private List<PivotViewDrilledMember> drilledMembers = new List<PivotViewDrilledMember>(); public async Task onExpand(Microsoft.AspNetCore.Components.Web.MouseEventArgs args) { expandAll = true; drilledMembers = new List<PivotViewDrilledMember>(); } public void onCollapse(Microsoft.AspNetCore.Components.Web.MouseEventArgs args) { expandAll = false; drilledMembers = new List<PivotViewDrilledMember>(); } } In the code example above, when the “Expand All” button is clicked, the onExpand event method will be triggered. Within the event method, we set the ExpandAll property to true, thereby expanding all headers. Subsequently, in the onCollapse event method, we set the same property to false for collapsing all headers. Additionally, we reset the DrilledMembers property to an empty list because this property always works in vice-versa with respect to the ExpandAll property. By implementing this code, you can dynamically expand or collapse all headers in a Blazor Pivot Table based on your requirements. The following GIF image, which portrays the results of the code snippet mentioned above, GIF You can refer to this GitHub sample for a practical demonstration of this code. Conclusion I hope you enjoyed learning how to customize values in a Blazor Pivot Table based on specified conditions. You can also refer to our Blazor Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Blazor Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!