Skip to content

Power Grid

Gabi edited this page May 10, 2024 · 38 revisions

Power Grid is a table component providing advanced functionalities such as row grouping and pivoting. Unlike the grouping table, which load its data from foundsets, the dataset table load its data from a dataset.

Table of contents

Quick start

In order to fill data to the table, renderData should be called, with a dataset, that should have columns defined. The name of the columns from the dataset will be used to match the defined columns on the table, based on the column's dataprovider.

function onShow(firstShow, event) {
	var ds = databaseManager.convertToDataSet(foundset, ['orderid', 'shipcountry', 'orderdate']);
	elements.datasettable.renderData(ds);
}

Grid Height in Responsive Form

It can be used both in responsive forms and absolute forms. If used in responsive mode, its 'responsiveHeight' property must be set in Properties View (which is the fixed height it will occupy).

Adding a table in a flex-content layout and setting the table responsiveHeight property to 0, let the table grow up to 100% height of parent element (see more on flex-layout here). Used with other containers than flex-content layout in order to grow the table to 100% height, the parent element must have a known height.

Dynamic row rendering

Is it possible to dynamically render and style the rows depending on their content using the Power Grid *Func properties such as rowStyleClassFunc, groupRowRendererFunc table properties and the column's properties cellRendererFunc, cellStyleClassFunc. A common use case is to color a cell or a whole row differently depending of the row data.

The *Func in Power Grid are functions defined as String and evaluated client-side (in the Browser itself) by the Power Grid allowing to customize rows dinamically;

Example for the column's cellStyleClassFunc; a different styleClass is returned depending on the columnData.

(function cellStyleClassFuncStatusColor(rowIndex, rowData, field, columnData, event) {
   if (!columnData) {
      return "";
   }
   if (columnData) {
      switch (columnData) {
      case "New Order":
         return "label-tag text-info";
         break;
      case "Completed":
         return "label-tag text-success";
         break;
      case "Planned":
         return "label-tag text-info";
         break;
      default:
         break;
      }
   }
   return "label-tag text-info";
})

Note that such function will fully run in the browser therefore won't have access to any Servoy API or object; all the logic should be implemented based on the given parameters (index, rowData and columnData for column's *Func).

Warning: Code sent to the browser could be inlined, meaning any comments could interfere. It is recommended to avoid sending comments client-side.

Lazy loading

If lazy loading is enabled, when new rows are requested by the table, onLazyLoadingGetRows will be called, where after you get the new data, you must call appendLazyRequestData, that will push the new rows to the table. The second argument of appendLazyRequestData, lastRowIndex, is a number that tells the table component how many rows are on the server; when all rows are in the table, the number of rows from the table is equal with lastRowIndex, lazy loading will stop, onLazyLoadingGetRows won't be called anymore.

function onLazyLoadingGetRows(startRow, endRow, rowGroupCols, valueCols, pivotCols, pivotMode, groupKeys, filterModels, sortModels) {
...
dataset = databaseManager.getDataSetByQuery("example_data", sql, params, size);
var col = dataset.getColumnNames();
for (i = 0; i < col.length; i++) {
dataset.setColumnName(i + 1, col[i].toLowerCase());
}
// check if there is next row
params[params.length - 1] = endRow + 1;
var nextRow = databaseManager.getDataSetByQuery("example_data", sql, params, 1);
var lastRowIndex = -1;
if (nextRow.getMaxRowIndex() == 0) {
lastRowIndex = startRow + dataset.getMaxRowIndex();
}

elements.datasettable.appendLazyRequestData(dataset, lastRowIndex);
}

Using custom cell editor

It is possible to use a form as a custom editor, by setting the 'editType' of a column to 'FORM' and 'editForm' to the desired form. When a cell will enter edit mode, the form will be shown in a popup and the 'onColumnFormEditStarted' handler will be called; this is where you can setup the values displayed in the form. To update the edited cell value with the result of the form editor, the 'setFormEditorValue' api function should be used (ex. if you have a save/ok button in the editor, this is the function that you need to call to set the result of the editing). In order to stop the editing and close the form editor popup, the 'stopCellEditing' api should be used.

Column

Type Property Default Description
String headerGroup Header group, that this column will be part of.
String headerGroupStyleClass Header group style Class
String headerTitle The column's header text.
String headerStyleClass The column's header style Classes.
Number headerGroupIndex Position of header group, 0-based"; by default it is placed at the end.
String headerTooltip The column's header tooltip.
String dataprovider Name of the column from the dataset used to display data for this column.
String tooltip Name of the column from the dataset used to display tooltips for this column.
String styleClass Column style Classes.
Boolean visible true If the column is visible or not.
Number width 0 Set the column's width. Auto-size itself when the width is 0.
Number minWidth Set the column's minimum width.
Number maxWidth Set the column's maximum width.
Boolean enableRowGroup true Allow the user to group or ungroup the column.
Number rowGroupIndex -1 Set the rowGroupIndex to group on the column; the index defines the order of the group when there are multiple grouped columns. The index is 0-based. Set the rowGroupIndex to -1 when the column is not used as group criteria.
Boolean enablePivot false If the column can be used as pivot.
Number pivotIndex -1 Set this in columns you want to pivot by. If only pivoting by one column, set this to any number (eg 0). If pivoting by multiple columns, set this to where you want this column to be in the order of pivots (eg 0 for first, 1 for second, and so on).
String pivotComparatorFunc Function to sort the pivot columns. Arguments are always strings, the function should return -1 if valueA is smaller then valueB, 1, if greater and 0 if they are equals. Ex.: (function (valueA, valueB) { return 0 - valueA.localeCompare(valueB)})
String aggFunc Name of function to use for aggregation. One of [sum,min,max,first,last].
Boolean enableFilter false If text based filter should be visible.
Boolean enableSort true If the column can be sorted.
Boolean enableResize true If the column can be resized.
Boolean enableToolPanel true If the column should be visible in the tool panel.
Boolean autoResize true If the column should auto resize when the table's width is changing.
String cellStyleClassFunc Function to add style class to cell. Ex.: (function (idx, data, field, value) { return 'myStyle' }).
String cellRendererFunc Function to change the cell rendering. Ex.: (function (idx, data, field, value) { return '' + value + '' }).
String format Format string as used in Servoy, for the type set in formatType.
String formatType TEXT Type of data the format is applied on ( one of [TEXT, NUMBER, DATETIME] ).
String editType NONE Type of editing used for that column. Can be one of the followings: NONE, TEXTFIELD, DATEPICKER, FORM, CHECKBOX.
Form editForm Form used as custom editor.
String id Used to set the column id (colId) property in the serialized column state json string of getColumnState and onColumnStateChanged.
Map columnDef Map where additional column properties of ag-grid can be set (see https://www.ag-grid.com/javascript-grid-column-properties/ ).
Boolean exportDisplayValue false If exportData api should export the display value (with format applied) instead of the raw data of the dataset. You may also need to add the 'stringType' to the styleClass of the column to force the exported value to be string.
String valueGetterFunc Proxy function for getting the cell value from the model. Ex.: (function (idx, data, field, params) { return 'cell_value' }).
Boolean dndSource Allow dragging.
String dndSourceFunc Boolean function for allow/disallow dragging. Ex. (function (idx, data, field) { return data[field] == true }).

Dataset Table Properties

Type Property Default Description
Column columns List all columns to be used in table as dataprovider.
Number responsiveHeight 300 Table's height to be set in a responsive form. When responsiveHeight is set to 0, the table will use 100% height of the parent container.
Number rowHeight 25 The height in pixels of the table's rows.
String rowStyleClassFunc Function to add style class to row. Ex.: (function (idx, data, field, value, e) { return 'myStyle' }).
String styleClass ag-bootstrap Table style Classes.
Boolean visible true If the table is visible or not.
Boolean enableColumnResize true Allow the user to resize columns.
Boolean enableSorting true Enable column sorting by clickin on the column's header.
Boolean pivotMode false Pivoting allows you to take a columns values and turn them into columns.
IconConfig iconConfig Icons configuration options.
String groupStyleClass Grouped column style Classes.
Number groupWidth 0 Set the group column's width. Auto-size itself when the width is 0.
Number groupMinWidth Set the group column's minimum width.
Number groupMaxWidth Set the group column's maximum width.
Boolean useLazyLoading false If lazy loading should be used.
Boolean multiSelect false If multiselect can be used.
Number headerHeight 33 Height of the table header.
ToolPanelConfig toolPanelConfig Tool panel configuration options.
Map gridOptions Map where additional grid properties of ag-grid can be set (see https://www.ag-grid.com/javascript-grid-properties/ ).
Map localeText Map where locales of ag-grid can be set (see https://www.ag-grid.com/javascript-grid-internationalisation/). As values, beside simple texts, you can also use i18n values defined in Servoy, like i18n:myi18nkey.
String groupRowRendererFunc Function to customize group row rendering when gridOptions.groupUseEntireRow is set to true. Ex.: (function groupRowInnerRenderer(params) { var label = params.node.key; if(params.node.aggData) { label += ' ['; for(var agg in params.node.aggData) { var column = gridOptions.columnApi.getColumn(agg); label += column.aggFunc + '(' + agg + '): ' + params.node.aggData[agg] + ', ';}; label = label.substring(0, label.length - 2) + '] ';}; return label;}).
MainMenuItemsConfig mainMenuItemsConfig Main menu items configuration options.
String arrowsUpDownMoveWhenEditing NONE Defines action on TEXTFIELD editor for up/down arrow keys. Can be one of the followings: NONE - editor's caret moves to start/end, NEXTCELL - starts editing the cell from the previos/next row, same column, if editable, else it just selects the row, NEXTEDITABLECELL - starts editing the cell from the first editable previous/next row, same column.
Boolean editNextCellOnEnter false If start editing next cell on ENTER (when in TEXTFIELD editor).
String isEditableFunc Callback that returns the editable state of a cell. Ex.: (function (idx, data, field) { return data[field] == true }).
String onDragOverFunc Callback when dragging over a row - returns one of the strings: 'copy', 'move', 'none' depending on the allowed drag operation. Ex. (function (src, dest, e) { return dest.id == 'myId' ? 'copy' : 'none';})
String onDragGetImageFunc Called when row(s) drag-n-drop is started, to get the drag image as an html code. Ex. (function (src, e) { return '<div>Dragging ' + src.length + ' records</div>';})

|

Dataset Table Events

Event Params Return Description
onRowSelected rowData:Object, selected:Boolean, event:JSEvent Event executed when the user selects a row.
onCellClick rowData:Object, columnId:String, cellData:Object, event:JSEvent Event executed when the mouse is clicked on a row/cell.
onCellDoubleClick rowData:Object, columnId:String, cellData:Object, event:JSEvent Event executed when the mouse is double clicked on a row/cell.
onCellRightClick rowData:Object, columnId:String, cellData:Object, event:JSEvent Event executed when the right mouse button is clicked on a row/cell.
onColumnStateChanged columnState:String Called when the columns state is changed.
onColumnDataChange rowIndex:Number, columnIndex:Number, oldValue:Object, newValue:Object, event:JSEvent, rowData:Object Boolean Event executed when the value of a cell is changed by editing. Return false to keep the cell in edit mode.
onLazyLoadingGetRows startRow:Number, endRow:Number, rowGroupCols:columnVO[], valueCols:columnVO[], pivotCols:columnVO[], pivotMode:Boolean, groupKeys:String[], filterModels:filterModelVO[], sortModels:sortModelVO[] Called when lazy loading is used, and new rows are requested to display.
onReady Event executed when the table is ready to be shown.
onColumnFormEditStarted rowIndex:Number, columnIndex:Number, value:Object Event executed when the column's form editor is started.
onRowGroupOpened groupColumnIndexes:Number[], groupKeys:String[], isOpened:Boolean Event executed when group is opened/closed
onDrop sourceRows:Object[], targetRow:Object, event:JSEvent Called when a row is dropped as a result of a drag-n-drop.

Dataset Table API

Method Params Return Description
renderData dataset:Dataset, pks:String[] Fills the table with data from a dataset. The column name from the dataset is used to match on the component column id. pks are optional list of dataprovider names, needed in case of using apis: updateRows and deleteRows (only NG2).
newColumn id:String, index:Number Column Creates a new column.
deleteColumn id:String Deletes column with id.
getColumn id:String, forChange:Boolean Column Gets column with id, if forChange is true, the returned column's properties can be changed.
getAllColumns Column[] Returns all the columns.
moveColumn id:String, index:Number Moves column with id to the 0-based index
exportData fileName:String, skipHeader:Boolean, columnGroups:Boolean, skipFooters:Boolean, skipGroups:Boolean, asCSV:Boolean Triggers a file download with the exported data in excel format. Check the column property exportDisplayValue if you want to export the values formatted according to the column's format property.
getColumnState String Returns a json object as string with the current state of the columns.
getSelectedRows Object[] Returns the selected rows.
setSelectedRows rowIndexes:Number[] Sets selected rows (0-based).
restoreColumnState columnState:String Restore column state from json string columnState. It won't re-create deleted columns.
appendLazyRequestData dataset:Dataset, lastRowIndex:Number Used inside onLazyLoadingGetRows, to append new rows to the table.
editCellAt rowindex:Number, columnindex:Number Start cell editing (only works when the table is not in grouping mode). 'rowindex' is the row index of the editing cell (0-based), 'columnindex' is the column index in the model of the editing cell (0-based)
stopCellEditing cancel:Boolean If a cell is editing, it stops the editing; use cancel 'true' to cancel the editing (ie don't accept changes).
getExpandedGroups groups:Object Returns currently expanded groups as an object like {expandedGroupName1:{}, expandedGroupName2:{expandedSubGroupName2_1:{}, expandedSubGroupName2_2:{}}}
setExpandedGroups groups:Object Sets expanded groups
newRows rowsData:Object[], appendToBeginning:Boolean Create new rows (only NG2).
updateRows rowsData:Object[] Update rows - in order to work, pks needs to be set using renderData, and the rowsData objects needs to have pk (only NG2).
deleteRows rowsKey:Object[] Delete rows - in order to work, pks needs to be set using renderData, and the rowsKey objects needs to have pk (only NG2).
scrollToRow rowData:Object Scroll viewport to matching row. rowData should have at least on attribute, used to find the viewport row to scroll to.
isPivotMode boolean Returns pivot mode state.
addAggCustomFuncs aggFuncs:Object Add custom aggregate functions. Ex.: addAggCustomFuncs({ myAggregate: '(function (valuesArray) { return myAggValueNumber })'})