▦K2 Advanced GridsDeveloper Portal / 0.23
Documentation / Developer reference

JavaScript API

This reference is intended for developers who want to control K2 Advanced Grids programmatically through their own JavaScript and build more advanced solutions on top of the component. Use it to integrate grid behavior with custom controls, application logic, reporting and existing K2 SmartForms.

Applies to Engine 1.0.0-beta.1.0. The API operates on the current browser Runtime and its loaded ListView records. It is not a server API, a SmartObject query interface or an authorization mechanism. See Configuration reference for module settings.

Entry points and initialization

Method / signatureReturnsBehavior and prerequisites
K2AdvancedGrids.versionstringEngine version.
K2AdvancedGrids.instanceobject | nullCurrent instance; null before initialization or after destroy.
K2AdvancedGrids.discover()ArrayReturns discovered Runtime grids: areaItemId, runtimeName, viewDefinitionId; discovery does not imply enhancement is enabled.
K2AdvancedGrids.start(config)objectStarts the engine with a configuration object; destroys any current instance first. Use only for deliberate initialization or restart.

The legacy global K2GridFiltersV2 refers to the same API object. The external loader already starts the engine; do not call start again on every K2 rule. Invoke custom code only after initialization and after the target ListView is registered.

{
  const api = window.K2AdvancedGrids;
  const ag = api?.instance;
  if (!ag) throw new Error('K2 Advanced Grids is not initialized');
  console.table(api.discover());
  console.table(ag.inspect().map(g => ({ id: g.id, rows: g.rows })));
}

Grid and column identifiers

Instance methods take the Runtime areaItemId as id, not the view definition ID or display name. Resolve the target explicitly when several ListViews share a form. Column methods generally accept a key, name or title; AutoFit accepts key or title. Use the actual key for ambiguous names. See Grid discovery and Multiple ListViews.

{
  const ag = K2AdvancedGrids.instance;
  const id = '9ec19162-70c7-1217-2d6c-fbe16e7f0afa'; // demo only
  const grid = ag.inspect().find(g => g.id === id);
  if (!grid) throw new Error('Target grid is not registered');
  console.table(grid.columns);
  console.table(grid.columnVisibility);
}

Lifecycle and diagnostics

Method / signatureReturnsBehavior and prerequisites
refresh()undefinedRe-resolves configuration and re-renders registered grids. Does not execute a K2 List method or retrieve new database records.
inspect()ArrayReturns diagnostic objects for registered grids; do not mutate returned nested objects.
clear(id?)undefinedClears advanced filters for the specified grid, or all registered grids when id is omitted. Does not clear grouping, layout or native K2 filters.
destroy()undefinedDisconnects observer and listeners, cleans up enhanced grids and clears the current instance. Restart explicitly or reload the form.

inspect() includes id, rows, columns (key, name, title, type, mode), filters (count), pagination, aggregation, layout, columnOrder, pinning, columnVisibility, preferences, conditionalFormatting, dataVisualization, cellMerging, rowGrouping and cardView. Some values may be absent when modules are disabled; layout may contain DOM references. Treat the diagnostic shape as Beta-specific.

{
  const ag = K2AdvancedGrids.instance;
  console.table(ag.inspect().map(g => ({
    id: g.id, loaded: g.rows, filters: g.filters,
    matching: g.pagination?.matching,
    mode: g.cardView?.mode, preferences: g.preferences?.status
  })));
}

Column management and layout

Method / signatureReturnsBehavior and prerequisites
setColumnVisible(id, key, visible)booleanRequires column management; cannot hide required columns or the final visible column.
resetColumns(id)booleanRestores configured default visibility, not necessarily all columns.
moveColumn(id, key, target, after=false)booleanMoves before target by default, after when true. Requires reordering and user reordering allowed; both columns visible and in the same pinning zone.
resetColumnOrder(id)booleanResets order to configured initial order; requires reordering.
setColumnPinned(id, key, side)booleanside: start, end, or null to unpin. Requires pinning and user pinning allowed; respects maximum pinned columns.
resetPins(id)booleanClears pin overrides and reapplies configured defaults; false for unknown grid.
autoFit(id, key)booleanRequires active resizing layout; measures loaded cell content and header, subject to width limits.
resetWidths(id?)undefinedClears width overrides for one grid or all grids, restoring configured widths.
{
  const ag = K2AdvancedGrids.instance;
  const id = 'REPLACE_WITH_YOUR_AREAITEMID';
  console.log(ag.setColumnVisible(id, 'Budget Variance', true));
  console.log(ag.setColumnPinned(id, 'Order Number', 'start'));
  console.log(ag.moveColumn(id, 'Order Amount', 'Budget Variance'));
  console.log(ag.autoFit(id, 'Vendor Name'));
}

Related training: Column visibility, Column pinning, Column reordering, AutoFit.

Grouping and presentation mode

Method / signatureReturnsBehavior and prerequisites
setGrouping(id, keys)booleanRequires rowGrouping.enabled. keys is an array of column keys, names or titles; [] clears grouping. Resets expansion state and page; unknown keys are ignored by the resolver. true does not prove all keys matched.
setCardMode(id, mode)booleanRequires cardView.enabled. mode is table or cards. Reapplies presentation and saves preferences when enabled.
{
  const ag = K2AdvancedGrids.instance;
  const id = 'REPLACE_WITH_YOUR_AREAITEMID';
  ag.setGrouping(id, ['Department', 'Status']);
  ag.setCardMode(id, 'cards');
  // Return to a flat table when needed:
  // ag.setGrouping(id, []);
  // ag.setCardMode(id, 'table');
}

See Row grouping and Card view. There is no dedicated public API in this release for setting filter predicates, page index, group expansion, row selection or invoking arbitrary K2 rules. Use the existing UI and native K2 rules rather than private DOM manipulation.

Personal preferences

Method / signatureReturnsBehavior and prerequisites
savePreferences(id)booleanWrites supported layout settings to localStorage if configured and available; false when unavailable or not initialized.
resetPreferences(id)booleanRemoves the stored preference key and resets layout, grouping, card mode and pagination state to configured defaults. Does not clear active filters.

Many layout operations save preferences automatically; a temporary Console experiment can therefore persist. Use a dedicated test configuration or disable preferences before experiments. See Personal preferences.

{
  const ag = K2AdvancedGrids.instance;
  const id = 'REPLACE_WITH_YOUR_AREAITEMID';
  console.log(ag.savePreferences(id));
  // Explicit user-requested reset only:
  // console.log(ag.resetPreferences(id));
}

CSV and native Excel export

Method / signatureReturnsBehavior and prerequisites
buildCSV(id, options?){text, records, columns} | nullBuilds CSV in memory without downloading. text is the CSV string.
exportCSV(id, options?){fileName, records, columns} | falseBuilds CSV and requests a browser download.
buildXLSX(id, options?){blob, records, columns} | nullBuilds an XLSX Blob without downloading.
exportXLSX(id, options?){fileName, records, columns} | falseBuilds XLSX and requests a browser download.

All four methods require export.enabled on the target grid. Build methods return null for an unknown or disabled grid; download methods return false. Invalid scope, column selection or CSV delimiter can throw. A returned file name indicates a download was requested, not that the file was saved successfully.

Options override the grid export settings for that call; nested csv and excel options are merged separately. Supported scopes: loaded, filtered, page. Columns: visible, all. Other shared options include fileName, appendTimestamp and preserveColumnOrder. CSV options: csv.delimiter (comma, semicolon, tab or pipe), csv.includeBOM. XLSX options: includeSummary, includeGrouping, includeFormatting; excel.sheetName, excel.autoFilter, excel.autoFitColumns, excel.freezeHeader, excel.freezePinned, excel.nativeConditionalFormatting. See Native Excel export and CSV export.

{
  const ag = K2AdvancedGrids.instance;
  const id = 'REPLACE_WITH_YOUR_AREAITEMID';
  console.table(['loaded', 'filtered', 'page'].map(scope => {
    const data = ag.buildCSV(id, { scope, columns: 'visible' });
    if (!data) throw new Error('Export unavailable');
    return { scope, records: data.records, columns: data.columns };
  }));
}
{
  const ag = K2AdvancedGrids.instance;
  const id = 'REPLACE_WITH_YOUR_AREAITEMID';
  const result = ag.exportXLSX(id, {
    scope: 'filtered', columns: 'visible', fileName: 'PurchaseOrders',
    includeSummary: true, includeGrouping: true, includeFormatting: true,
    excel: { nativeConditionalFormatting: true }
  });
  console.log(result);
}

The page scope follows the engine’s current export dataset, not the number of DOM nodes visible in the viewport. Group collapse is a presentation state; filtered export can include collapsed records. Native Excel bars and scales are Excel rules, whereas exported status formatting is a cell-style snapshot; do not assume pixel-identical output.

Runtime configuration changes

The engine holds the configuration object passed to start. Mutate that existing object and call refresh to re-resolve settings. Reassigning the global variable alone does not replace the captured configuration. Per-grid overrides can take precedence over defaults. Some user state persists independently of configuration.

{
  const cfg = K2AdvancedGridsConfig;
  cfg.defaults.aggregation.position = 'bottom';
  K2AdvancedGrids.instance.refresh();
}

Integration boundaries and safe usage

Call methods from custom application scripts only after the loader is ready. Check return values and catch export errors. Do not use destroy as a refresh shortcut. The exposed test object (matches, val, compare) is intended for internal diagnostics, not application integration. No stable event subscription API is documented for Beta 1.0. Client-side controls do not enforce access permissions; keep authorization and business validation in K2 and backend services. See Disclaimer.

Verification: signatures and return contracts were audited against the frozen engine source. Training screenshots verify representative Runtime and export scenarios; the complete set of API calls has not been independently exercised in a live K2 environment. The examples use the demo grid identifier or an explicit placeholder; replace it with your own.

Enlarged screenshot