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 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 Integrating a Syncfusion JavaScript Pivot Table into a Blazor web application significantly enhances the data analysis capabilities. This is achievable by using a JavaScript interop that invokes JavaScript methods from the Blazor web application. In this article, we will guide you through the procedure, providing a step-by-step example. Step 1: Create an HTML element First, you must place a div element on your razor page (i.e., Index.razor), where the Pivot Table will be displayed. The id attribute of the div should be designated as a unique identifier to ascertain that JavaScript initializes the Pivot Table in this specific element correctly. Here is a code example of how you can create an HTML div element: [index.razor] @page "/" <div class="control-section"> <div class="content-wrapper pivot-container"> <div id="@ID" class="pivot-table"></div> </div> </div> [index.razor.cs] public partial class Index { private string ID = "PivotTable"; } Step 2: Defining the data source After creating the HTML div element, it is necessary to define the data source in your Razor page (i.e., Index.razor.cs) to configure the pivot table control. This can be done by creating a class that represents the data structure, in this case, ProductDetails. This class should contain properties that represent the necessary data fields for the pivot table, such as “Sold”, “Amount”, “Products”, “Year”, and “Quarter”. Here is an example of how to define a data source for the pivot table using a class called ProductDetails in the razor page: [index.razor.cs] namespace BlazorApp1.Pages { public partial class Index { public class ProductDetails { // Define properties that represent the data fields public int Sold { get; set; } public double Amount { get; set; } public string Country { get; set; } public string Products { get; set; } public string Year { get; set; } public string Quarter { get; set; } // Method to generate a list of product details public static List<ProductDetails> GetProductData() { // Add product details to the list List<ProductDetails> productData = new List<ProductDetails>(); productData.Add(new ProductDetails { Sold = 31, Amount = 52824, Country = "France", Products = "Mountain Bikes", Year = "FY 2015", Quarter = "Q1" }); // ... additional data reference return productData; } } } } Step 3: Serialize the data source After you have determined the necessary data source, you will need to convert it into a JSON string. This conversion is essential for the JavaScript code to accurately read and use the data within the Pivot Table. This can be accomplished by using the JsonSerializer.Serialize method within the OnInitializedAsync lifecycle method. Here is an example of how to convert a data source into JSON format: [index.razor.cs] using System.Text.Json; namespace BlazorApp1.Pages { public partial class Index { protected List<ProductDetails> Data { get; set; } private string dataSource; protected override async Task OnInitializedAsync() { // Assuming GetProductData is a static method that returns a list of ProductDetails. Data = ProductDetails.GetProductData(); // Serialize the Data list to a JSON string. dataSource = JsonSerializer.Serialize(Data); } } } Step 4: Add stylesheet and script resources Before initializing the pivot table, you need to include the Syncfusion styles and scripts in your ~/Pages/Host.cshtml file. This is typically done by adding the references inside the <head> tag of the ~/Pages/Host.cshtml file. Here is the code snippet how you can include the styles and scripts resources: [Host.cshtml] <!-- Syncfusion javascript control styles --> <link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/24.1.41/fluent.css" /> <!-- Syncfusion javascript control scripts --> <script src="https://cdn.syncfusion.com/ej2/24.1.44/dist/ej2.min.js" type="text/javascript"></script> Step 5: Configure the javascript pivot table control Once you’ve included the necessary references, you’ll need to create a JavaScript file (e.g., pivotview.js) and define a function called integratePivotTable. This function takes the ID of the DOM element and the serialized data as arguments. Within this function, initialize the pivot view control with serialized data from the Blazor web application. [pivotview.js] function integratePivotTable(id, data) { // Parse the incoming data from a JSON string into an object var pivotData = JSON.parse(data); // Initialize pivot table component var pivotTableObj = new ej.pivotview.PivotView({ // Configure the data source settings for the pivot table dataSourceSettings: { // Assign the parsed data here dataSource: pivotData columns: [{ name: 'Year' }, { name: 'Quarter' }], values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount'}], rows: [{ name: 'Country' }, { name: 'Products' }], }, width: '100%', height: 290, gridSettings: { columnWidth: 140 }, showFieldList: true }); // Append the pivot table to the DOM element with the specified ID pivotTableObj.appendTo('#' + id); } In the code example mentioned, we parse the retrieved data into a JavaScript object within the integratePivotTable method. Following this, we initialize pivot table component using ej.pivotview.PivotView() instance and assign the parsed data to the dataSource property of the dataSourceSettings. Subsequently we added the fields to row, column, values axes. Finally we appended this pivot table instance to the retrieved DOM element using the appendTo method. This action will render the pivot table in the Blazor web application. Step 6: Include the JavaScript file in your Blazor application Once you have initialized the pivot table in the pivotview.js file, you must reference it within the <body> tag of the ~/Pages/Host.cshtml file. Here’s an example of how you can accomplish this: [Host.cshtml] <html> <body> <script src="scripts/pivotview.js"></script> </body> </html> Step 7: Invoke JavaScript method in razor page Once you’ve included the pivotview.js file, you can invoke the integratePivotTable method on your razor page (i.e., Index.razor.cs) using JavaScript interop. Below is an example of how you can invoke the integratePivotTable method in your razor file: [Index.razor] using Microsoft.JSInterop; namespace BlazorApp1.Pages { public partial class Index { // Inject the IJSRuntime service that allows invoking JavaScript method [Inject] protected IJSRuntime JSRuntime { get; set; } protected override async Task OnAfterRenderAsync(bool firstRender) { // Here we we ensure the JavaScript method is only called once after the component is first rendered. if(firstRender) { // Invoking the 'integratePivotTable' JavaScript method and passing the ID and Serialized dataSource as parameters await JSRuntime.InvokeVoidAsync("integratePivotTable", ID, dataSource); } } } } In the above code, we first injected the IJSRuntime service using the [Inject] attribute. This service allows us to interact with JavaScript code from our razor page. Subsequently, within the OnAfterRenderAsync lifecycle method, we checked if it was the first render of the razor component by using the firstRender parameter. If this is indeed the first render, we used the InvokeVoidAsync method to invoke the integratePivotTable JavaScript method, passing the ID of the DOM element and the serialized data as parameters. This action integrates the JavaScript pivot table into a Blazor web application. Step 8: Run your application Now, compile and run your Blazor project you can see that the Syncfusion JavaScript Pivot Table component has been integrated and is functioning within your Blazor web application. The following screenshot portrays the results of the code snippets mentioned above, You can refer to this GitHub sample for a practical demonstration of this code. Conclusion I hope you enjoyed learning how to to integrate a JavaScript Pivot Table into a Blazor web application. 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 ASP.NET Core Pivot Table, you can dynamically edit the value cells by setting the allowEditing property in e-editSettings tag to true. However, in certain scenarios, you may want to update the data source in your controller after performing edit operations. This can be achieved by sending the edited data back to a controller file using jQuery AJAX. In this article, we will guide you through the process with code examples. Step 1: Defining the data source in the controller First, you need to create the data source in your controller in order to configure the pivot table control. To do this, create a class that represents the data structure, which in our scenario is OrderDetails. This class will contain properties that represent the necessary data fields for the pivot table, such as “Country”, “UniqueID”, “Amount”, and “Year”. Here is an example of how to define a data source for the pivot table using a class called OrdersDetails in the controller (i.e., HomeController.cs) file: [HomeController.cs] using Microsoft.AspNetCore.Mvc; public class HomeController : Controller { public class OrdersDetails { // List to store order details. public static List<OrdersDetails> order = new List<OrdersDetails>(); // Properties to define the data fields. public OrdersDetails(int UniqueId, string Country, string Year, int Amount) { this.UniqueID = UniqueId; this.Country = Country; this.Year = Year; this.Amount = Amount; } public static List<OrdersDetails> GetAllRecords() { // Check if the list is empty to avoid duplicate data. if (order.Count() == 0) { // Populating the order list with sample data. order.Add(new OrdersDetails(1, "France", "FY 2015", 52824)); } return order; } // Properties to define the data fields. public string Country { get; set; } public int ? UniqueID { get; set; } public int Amount { get; set; } public string Year { get; set; } } } Step 2: Initializing the pivot table control After defining the required data source in your controller file (i.e., HomeController), it’s essential to initialize the pivot table control on the cshtml page (i.e., ~/Pages/Index.cshtml) using that data source. The following code example demonstrates how to assign the data source from the controller file to the cshtml page: [HomeController.cs] using Microsoft.AspNetCore.Mvc; public class HomeController : Controller { public IActionResult Index() { // Fetch your data here var currentData = OrdersDetails.GetAllRecords().ToList(); // Store the data in the ViewBag with a key to be accessed in the cshtml page. ViewBag.datasource = currentData; // Return the corresponding view. return View(); } } [Index.cshtml] <ejs-pivotview id="PivotView"> <e-datasourcesettings dataSource="@ViewBag.datasource"> <e-rows> <e-field name="Country"></e-field> </e-rows> <e-columns> <e-field name="Year"></e-field> </e-columns> <e-values> <e-field name="Amount"></e-field> </e-values> </e-datasourcesettings> </ejs-pivotview> In the controller, we retrieve the previously defined data source and store it in the currentData variable. This data is then assigned to ViewBag.datasource, which will be accessible on the cshtml page. Subsequently, on the cshtml page, we define the pivot table control using the ejs-pivotview tag and set its dataSource property to ViewBag.datasource to utilize the data passed from the controller. Step 3: Including jQuery library Once you’ve initialized the pivot table, you need to use a JavaScript library, like jQuery, to make an Ajax request to the controller file in order to update a data source after performing edit operations in a pivot table. To incorporate the jQuery library into a pivot table, it is necessary to include the following script references in the application’s ~/Views/Shared/Layout.cshtml file: [Layout.cshtml] <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js" asp-fallback-src="~/lib/jquery/dist/jquery.min.js" asp-fallback-test="window.jQuery" crossorigin="anonymous" integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk"> </script> Step 4: Define the data transfer object After adding the jQuery library, you need to send the edited data from the cshtml page (i.e., ~/Pages/Index.cshtml) to the controller (i.e., HomeController.cs). To accomplish this, first you need to define a Data Transfer Object (DTO) in the controller. This will carry the edited data from the cshtml page to the controller. [HomeController.cs] public class DataResult { // Update properties of your entity here public List<OrdersDetails> AddedData { get; set; } public List<int> ModifiedIndex { get; set; } } The DataResult class includes two properties: AddedData, which holds the edited data, and ModifiedIndex, which may carry the indices of the modified rows or other relevant information. Step 5: Write a controller action After defining the data transfer object, you need to handle the incoming edited data. To achieve this, create an action method (i.e., BatchUpdate) that the AJAX call will target. Here is an example of how to receive the edited data and perform CRUD operations: [HomeController.cs] [HttpPost] public IActionResult BatchUpdate([FromBody] DataResult DataResult) { // Here we get the current data source currentData = OrdersDetails.GetAllRecords().ToList(); for (var i = 0; i < DataResult.ModifiedIndex.Count; i++) { if (DataResult.AddedData.Count > 0) { for (var j = 0; j < DataResult.AddedData.Count; j++) { if (currentData[DataResult.ModifiedIndex[i]].UniqueID == DataResult.AddedData[j].UniqueID) { // Here we update the modified data to data source currentData[DataResult.ModifiedIndex[i]] = DataResult.AddedData[j]; } else { // Here we include the newly added data to the data source DataResult.AddedData[j].UniqueID = currentData.Count + 1; currentData.Add(DataResult.AddedData[j]); } } } else { // Here we remove the data from data source currentData.RemoveAt(DataResult.ModifiedIndex[i]); } } return Json(new { result = currentData, count = currentData.Count }); } In the above, we iterate over the ModifiedIndex property of the DataResult class, which contains the indexes of the edited records. For each index, we check if there is any newly added or edited data by checking the count of the AddedData property. If there is, we iterate over the AddedData collection and check whether the UniqueID of the added data already exists in the current data source. If this condition is met, we update the corresponding data in the data source by assigning the added data to the currentData list. Otherwise, we assign a new UniqueID to the added data and include it in the data source by appending it to the currentData list. Should there be no added data, we remove the data at the modified index from the currentData list, effectively deleting it from the data source. Step 6: Send edited data using jQuery In the cshtml page (i.e., ~/Pages/Index.cshtml), you need to set up the jQuery AJAX call in a script within the editCompleted event. This event triggers when value cells are edited completely. Here is an example of how to send the data to the controller: <ejs-pivotview id="PivotView" height="300" editCompleted="editCompleted"> <e-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Normal"></e-editSettings> </ejs-pivotview> <script> function editCompleted(args) { $.ajax({ url: "/Home/BatchUpdate", type: "POST", data: JSON.stringify({ 'addedData': args.currentData, 'modifiedIndex': args.previousPosition }), dataType: 'json', contentType: 'application/json; charset=UTF-8', success: function (response) { console.log("Edit Completed"); } }); } </script> In this code snippet, we are using jQuery’s $.ajax method to send a POST request to the BatchUpdate action method in the HomeController. The args.currentData contains the newly edited data, and args.previousPosition contains the indexes of the modified data rows. This data is serialized into JSON format and sent to the controller. After the controller receives the edited data, the data source can be updated as mentioned in the previous step. 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 update the data source after performing editing in an ASP.NET Core Pivot Table. You can refer to our ASP.NET Core 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 ASP.NET Core 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: When working with pivot table, sometimes you might want to create a calculated field with a conditional formula. Let’s assume you have fields designated as “A” and “B.” You want to create a calculated field based on the values of these fields using a conditional formula. For instance, the formula would be Sum(A) === 0 ? Sum(B) : Sum(A). However, you may notice that after creating the calculated field, the grand total value is not summarized accurately. Instead, it shows the grand total value for one of the fields used in the formula (i.e., “A”). This occurs because the grand total values of the calculated field are always determined based on the grand total values of the fields used in the formula, not by aggregating each value in the calculated field. This is the actual behavior of the calculated field in our Syncfusion Pivot Table. In this article, we will discuss how to customize the grand total value of a calculated field in a pivot table by using a workaround technique. Customize the grand total value of a calculated field In order to customize the grand total value of a calculated field, you need to use the aggregateCellInfo. This event is triggered during the rendering of each cell in the pivot table and allows you to change the value of each cell. [app.component.html] <ejs-pivotview #pivotview id="PivotView" (aggregateCellInfo)="aggregateCellInfo($event)" (dataBound)="dataBound($event)"> </ejs-pivotview> [app.component.ts] import { PivotViewAllModule } from '@syncfusion/ej2-angular-pivotview'; export class AppComponent { public dataSourceSettings: IDataOptions; public columnHeader = {}; aggregateCellInfo(args) { // Targeting a specific calculated field with the name 'Valuation' if ( args.fieldName === 'Valuation' && args.value && args.rowCellType !== 'subTotal' && args.row.colIndex !== undefined ) { // Check if the current row is not a 'grand sum' if (args.rowCellType !== 'grand sum') { // Check if the column's unique name is not yet in the 'customTotal' object if (!this.columnHeader[args.column.valueSort.levelName]) { // If not present, initialize the value for this column's unique name this.columnHeader[args.column.valueSort.levelName] = args.value; } else { // If present, add the current value to the existing total this.columnHeader[args.column.valueSort.levelName] += args.value; } } else { // If row cell type is equal to 'grand sum', we assign the summarized total value args.value = this.columnHeader[args.column.valueSort.levelName]; } } } dataBound() { this.columnHeader = {}; } ngOnInit(): void { this.dataSourceSettings = { values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }, { name: 'Valuation', caption: 'Valuation', type: 'CalculatedField', }], calculatedFieldSettings: [ { name: 'Valuation', formula: '"Sum(Sold)" == 0 ? "Sum(Amount)" : "Sum(Sold)"', formatString: 'N2', }, ], showColumnGrandTotals: false }; } } Here’s a breakdown of how the code works: First, we initialize an empty object named “columnHeader” to store the aggregated values of the calculated field. Then, within the aggregateCellInfo event, we target the specific calculated field (i.e., “Valuation”) using the fieldName property. Next, we check if the row cell type is not a sub-total and that the row is not a grand sum using the rowCellType and row.type properties, respectively. If these conditions are satisfied, we check if the current column-level name is already present in the “columnHeader” object. If it is not present, we add the column level name as a key and the current cell value as the corresponding value in the columnHeader object. If the column level name is already in the “columnHeader” object, we add the current cell value to the existing one. Finally, when a cell belongs to a grand total row, we assign the summarized total value from the “columnHeader” object to the current grand value by using the “value” property and clear the “columnHeader” object within the dataBound event. The following screenshots illustrate the difference 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 I hope you enjoyed learning how to customize the grand total value of a calculated field 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 pivot tables, you can dynamically sort a specific value field and its aggregated values on either the row or column axis in both ascending and descending order. It can be enabled by setting the enableValueSorting property in the Angular Pivot Table to true. By default, the sorting order will be from descending to ascending. When you first click a value field header, it sorts the values in descending order. Clicking the same value field header again will sort the values in ascending order. However, in certain scenarios, you may want to clear the sorting by clicking a third time on the same value field header. There isn’t a direct option to accomplish this within the pivot table. Although this can be achieved through a workaround technique using the cellClick event. In this article, we will guide you through the process with a code example. Using the cellClick event to clear sorting To clear the value sorting after the third click on a specific value field header in a pivot table, you need to use the cellClick event. This event is triggered when clicking a cell in the pivot table, allowing you to clear the current sort order. [app.component.html] <ejs-pivotview #pivotview id="PivotView" enableValueSorting='true' (cellClick)="cellClick($event)"> </ejs-pivotview> [app.component.ts] import { PivotView } from '@syncfusion/ej2-pivotview'; export class AppComponent { public pivotObj: PivotView; @ViewChild('pivotview') public pivotObj: PivotView; // Define the cellClick event handler cellClick(args) { // Here we clear the sorting after the "Ascending" order is applied, However, you can modify this condition according to your specific need. if (args.currentCell.classList.contains('e-valuesheader') && this.pivotObj.dataSourceSettings.valueSortSettings.sortOrder === 'Ascending') { this.pivotObj.setProperties( { dataSourceSettings: { // Here we reset the sorting valueSortSettings: { sortOrder: 'None', headerText: '' }, }, }, true ); // Refreshing the data to reflect the changes on the UI. this.pivotObj.refreshData(); } } In the above code example, within the cellClick event method, we verify whether the clicked cell is a value field header by targeting the built-in class name (i.e., e-valuesheader ). Subsequently, we check the sort order of the value field, which is “Ascending”. If it is, we utilize the setProperties method, which allows us to set multiple properties simultaneously. With this method, we reset the sorting by setting the value of the sortOrder property to “None” and the headerText property to an empty string. The second parameter of setProperties is set to true to ensure the changes. Finally, we call the refreshData method to update the pivot table with the cleared sort settings. By implementing this code in your project, you can clear value sorting by clicking a specific value field header in a pivot table for the third time. Things to remember In the above workaround technique, we clear the value header sorting after the “Ascending” order is applied. While sorting, the sort order cycle will be as follows: descending, ascending, and then none. However, if you want to clear the sorting after the “Descending” order, simply change the above ‘If’ condition within the cellClick event to check for the “Descending” order, like this: this.pivotObj.dataSourceSettings.valueSortSettings.sortOrder === 'Descending'. This will effectively remove the sorting after the “Descending” order has been applied. The following GIF image, which portrays the results of the above-mentioned snippets, GIF For a practical demonstration, refer to the sample of stackblitz. Conclusion I hope you enjoyed learning how to dynamically clear the value sorting 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 pivot table, you can export the data as PDF, Excel, or CSV documents. However, in certain scenarios, you may want to export all the underlying data, including the data for the collapsed field members that is not displayed on the user interface (UI). The default behavior of the JavaScript Pivot Table is to export only the data that is visible in the UI. This article will guide you on how to export the entire data from a pivot table, including the data associated with collapsed field members, by using the beforeExport event. Please note that this procedure is applicable only to engine exports and is not suitable for grid exports. Export all data To export all data from a pivot table, including the child members of collapsed fields, you can utilize the beforeExport event. This event allows you to manipulate the data before it is exported as PDF, Excel, or CSV documents. Here is a code example that demonstrates how you can use the beforeExport event: [index.js] var pivotObj = new ej.pivotview.PivotView({ allowExcelExport: true, allowPdfExport: true, beforeExport: (args) => { // Store the currently expanded row/column headers let member = pivotObj.dataSourceSettings.drilledMembers; // Expand all fields in the dataSourceSettings to include all child members pivotObj.setProperties( { dataSourceSettings: { expandAll: true, drilledMembers: []}}, true ); // Generate the grid data with all members expanded pivotObj.engineModule.generateGridData(pivotObj.dataSourceSettings, true) // Assign the expanded data to the `dataCollections` property for export args.dataCollections = [pivotObj.engineModule.pivotValues]; // Revert the dataSourceSettings to only show expanded members as before pivotObj.setProperties( { dataSourceSettings: { expandAll: false, drilledMembers: member}}, true ); } }); Here’s a breakdown of how the code works: First, we store the current drilledMembers, which represent the field headers that have been expanded in the Pivot Table UI. Then, within the setProperties method, we set the expandAll property to true and assign an empty array to drilledMembers within the dataSourceSettings. This is to ensure that all records, including those that were collapsed, will be considered for export. We also set the second parameter of setProperties to true to ensure the changes. Next, we call the generateGridData method on the pivotObj.engineModule. This method applies the changes to the data source settings and regenerates the table data accordingly. Afterwards, we retrieve the expanded data from the pivotObj.engineModule.pivotValues property and assign it to the dataCollections property. This will export the entire data set from a pivot table, including the data associated with collapsed field members. As a final step, we set expandAll back to false and restore the original drilledMembers. This action ensures that the appearance and state of the pivot table in the user interface remain unchanged after the export process is complete. The following screenshot illustrates the difference between a pivot table and its exported documents, such as PDF, Excel, or CSV, Screenshots Pivot Table PDF Export Excel Export CSV Export 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 export all data from JavaScript Pivot Table including collapsed field members. 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!