# Defining Pivot Layouts

Canonical page: https://www.adaptabletools.com/docs/handbook-layouts-pivot-defining

- Pivot Layouts enable AG Grid instances with Pivoting to be defined
- All elements of pivoting are supported - Pivot Columns, Row Groups and Aggregations
- Pivot Layouts can also include Format Column styles
- Pivot Layouts can be defined at design-time through Initial Adaptable State, or created at runtime in the UI Wizard

[Layouts](https://www.adaptabletools.com/docs/handbook-layouts/index.md) · [Pivot Layouts](https://www.adaptabletools.com/docs/handbook-layouts-pivot/index.md) · [All Pivot Layout Topics](https://www.adaptabletools.com/docs/handbook-layouts-pivot/index.md#pivot-layout-topics).
Pivot concepts and client-side demos — [Pivot Layouts](https://www.adaptabletools.com/docs/handbook-layouts-pivot/index.md). **Server-Side Row Model** pivoting — [Server-Side Pivoting](https://www.adaptabletools.com/docs/dev-guide-row-models-server-pivoting/index.md) (not repeated here).

Pivot Layouts can be defined at design-time using [Pivot Layout Initial Adaptable State](https://www.adaptabletools.com/docs/technical-reference-layouts/index.md).

### Anatomy of an AdapTable Pivot Layout

#### Base Properties

[`PivotLayout`](https://www.adaptabletools.com/docs/reference/pivotlayout.md) object inherits from [`LayoutBase`](https://www.adaptabletools.com/docs/reference/layoutbase.md) (used also for Table Layouts) which contains these properties:

| Property | Type | Description |
| --- | --- | --- |
| [AutoSizeColumns](https://www.adaptabletools.com/docs/reference/layoutbase.md#autosizecolumns) | `boolean` | Whether Columns should autosize when Layout first loads |
| [ColumnFilters](https://www.adaptabletools.com/docs/reference/layoutbase.md#columnfilters) | [`ColumnFilter`](https://www.adaptabletools.com/docs/reference/columnfilter.md)`[]` | Collection of Column Filters to apply in Layout |
| [ColumnGroupValues](https://www.adaptabletools.com/docs/reference/layoutbase.md#columngroupvalues) | [`ColumnGroupValues`](https://www.adaptabletools.com/docs/reference/columngroupvalues.md) | Defines which Column Groups are expanded / collapsed |
| [ColumnHeaders](https://www.adaptabletools.com/docs/reference/layoutbase.md#columnheaders) | [`ColumnStringMap`](https://www.adaptabletools.com/docs/reference/columnstringmap.md) | Set of custom header names for some (or all) Columns |
| [ColumnPinning](https://www.adaptabletools.com/docs/reference/layoutbase.md#columnpinning) | [`ColumnDirectionMap`](https://www.adaptabletools.com/docs/reference/columndirectionmap.md) | Columns pinned to an edge. Each entry is a column id set to `'left'` or `'right'`. Columns absent from the map are not pinned. |
| [ColumnSizing](https://www.adaptabletools.com/docs/reference/layoutbase.md#columnsizing) | [`ColumnSizingMap`](https://www.adaptabletools.com/docs/reference/columnsizingmap.md) | Controls size (width or flex &amp; min/max) for Columns |
| [ColumnSorts](https://www.adaptabletools.com/docs/reference/layoutbase.md#columnsorts) | [`ColumnSort`](https://www.adaptabletools.com/docs/reference/columnsort.md)`[]` | Sorting to apply in the Layout |
| [GrandTotalRow](https://www.adaptabletools.com/docs/reference/layoutbase.md#grandtotalrow) | `'top' \| 'bottom' \| 'pinnedTop' \| 'pinnedBottom' \| boolean` | Where the grand total row is shown.<br/><br/>`'top'`, `'bottom'`, `'pinnedTop'` or `'pinnedBottom'`. `true` is the same as `'top'`. `false`, or omitting the property, turns the grand total row off. |
| [GridFilter](https://www.adaptabletools.com/docs/reference/layoutbase.md#gridfilter) | [`GridFilter`](https://www.adaptabletools.com/docs/reference/gridfilter.md) | Grid Filter to apply in Layout |
| [Name](https://www.adaptabletools.com/docs/reference/layoutbase.md#name) | `string` | Name of the Layout as it appears in the Layout toolbar and tool panel |
| [OpenCharts](https://www.adaptabletools.com/docs/reference/layoutbase.md#opencharts) | [`LayoutOpenChart`](https://www.adaptabletools.com/docs/reference/layoutopenchart.md)`[]` | AG Grid charts to open when this layout is selected (by chart UUID or name) |
| [RowGroupDisplayType](https://www.adaptabletools.com/docs/reference/layoutbase.md#rowgroupdisplaytype) | `RowGroupDisplayType` | How Row Groups are displayed: &#39;single&#39; - one hierarchical group Column; &#39;multi&#39; - a separate group Column per Row Grouped Column; &#39;groupRows&#39; - full-width group rows (no group column); defaults to &#39;single&#39; |
| [RowGroupValues](https://www.adaptabletools.com/docs/reference/layoutbase.md#rowgroupvalues) | [`RowGroupValues`](https://www.adaptabletools.com/docs/reference/rowgroupvalues.md) | Defines which Row Groups are expanded / collapsed |
| [RowSelection](https://www.adaptabletools.com/docs/reference/layoutbase.md#rowselection) | [`LayoutRowSelection`](https://www.adaptabletools.com/docs/reference/layoutrowselection.md)` \| false` | Defines Row Selection behaviour for Layout; if false, Row Selection is disabled; if undefined, GridOptions is used |
| [SuppressAggFuncInHeader](https://www.adaptabletools.com/docs/reference/layoutbase.md#suppressaggfuncinheader) | `boolean` | Hides the aggFunc in Column header: e.g. &#39;sum(Price)&#39; becomes &#39;Price&#39; |
| [IsReadOnly](https://www.adaptabletools.com/docs/reference/layoutbase.md#isreadonly) | `boolean` | Sets Entity to ReadOnly (overwriting a Strategy Entitlement of &#39;Full&#39;) |

#### Pivot Properties

The [`PivotLayout`](https://www.adaptabletools.com/docs/reference/pivotlayout.md) object additionally contains these properties which are specific to Pivot Layouts:

| Property | Type | Description |
| --- | --- | --- |
| [PivotAggregationColumns](https://www.adaptabletools.com/docs/reference/pivotlayout.md#pivotaggregationcolumns) | [`PivotAggregationColumns`](https://www.adaptabletools.com/docs/reference/pivotaggregationcolumns.md) | Columns showing aggregated values in Group Rows; 1st value in record is Column name, 2nd is either aggfunc (e.g. sum, avg etc.) or &#39;true&#39; (to use default aggfunc) |
| [PivotColumns](https://www.adaptabletools.com/docs/reference/pivotlayout.md#pivotcolumns) | `string[]` | Mandatory list of Columns to pivot (provide empty array if just displaying Aggregations) |
| [PivotColumnTotal](https://www.adaptabletools.com/docs/reference/pivotlayout.md#pivotcolumntotal) | [`PivotTotalPosition`](https://www.adaptabletools.com/docs/reference/pivottotalposition.md) | Display automatically calculated Totals within EACH Pivot Column Group, in the position specified |
| [PivotExpandLevel](https://www.adaptabletools.com/docs/reference/pivotlayout.md#pivotexpandlevel) | `number` | How deep to expand Pivot Columns (0 for none, 1 for 1st level only etc, -1 to expand all) |
| [PivotGrandTotal](https://www.adaptabletools.com/docs/reference/pivotlayout.md#pivotgrandtotal) | [`PivotTotalPosition`](https://www.adaptabletools.com/docs/reference/pivottotalposition.md) | Display automatically calculated Totals of all Pivot Columns, in the position specified |
| [PivotGroupedColumns](https://www.adaptabletools.com/docs/reference/pivotlayout.md#pivotgroupedcolumns) | `string[]` | Columns which are row-grouped when the Layout is applied |
| [PivotResultColumnsOrder](https://www.adaptabletools.com/docs/reference/pivotlayout.md#pivotresultcolumnsorder) | `string[] \| boolean` | Ordered list of Pivot Result Columns; set to `true` to track current display order, or provide custom list |
| [IsReadOnly](https://www.adaptabletools.com/docs/reference/pivotlayout.md#isreadonly) | `boolean` | Sets Entity to ReadOnly (overwriting a Strategy Entitlement of &#39;Full&#39;) |

The main properties required to create a Pivot Layout are:

- `PivotColumns` - columns which generate a Pivot Column Group for each distinct column value
- `PivotAggregationColumns` - columns which will display Aggregated Values (in Pivot Result Columns)
- `PivotGroupedColumns` - columns that AG Grid will use for Row Grouping

Developers can also provide `PivotGrandTotal` and `PivotColumnTotal` props which are used in [Pivot Total Columns](https://www.adaptabletools.com/docs/handbook-layouts-pivot-total-columns/index.md)

### Defining a Pivot Layout

These are the steps required to set up a standard Pivot Layout.

To add Sorting, Pinning and other features see the relevant sections in the [Table Layout Guide](https://www.adaptabletools.com/docs/handbook-layouts-table/index.md).

Choose something unique but relevant.

This is how AdapTable will refer to the Layout in the UI

`PivotColumns` is an array of (string) Column Ids.

AG Grid dynamically creates a Pivot Result Column for each unique value in each Pivot Column, and each set is displayed in the order provided here.

AdapTable **does not save** the actual Pivot Result Columns, since they are dynamically created, nor the order in which they are displayed

If you do not require Pivot Columns, **provide an empty array**.

`PivotGroupedColumns` is an array of (string) Column Ids.

The Columns will be row-grouped in the order provided.

Specify the [Row Group Expanded / Collapsed Behaviour](https://www.adaptabletools.com/docs/handbook-grouping-rows/index.md#expanded--collapsed-row-groups) as required.

`PivotAggregationColumns` defines Aggregations to display

It comprises an array of objects which contain 2 properties:

- a `ColumnId`  (string)
- either an `aggFunc` (e.g. sum) or *true* (to use default `aggFunc`)

Set the sizing for both Aggregation and Pivot Result Columns.

`ColumnSizing` is a map where the ColumnId is the key, and an object (to define sizing, using either Widths or Flex) is the value.

Alternatively use the `AutoSizeColumns` property to autosize all Layout Columns

```ts [[1, 18, "Name"],[2, 19, "PivotColumns"],[3, 20, "PivotGroupedColumns"],[3, 21, "RowGroupValues"],[4, 24, "PivotAggregationColumns"],[5, 34, "ColumnSizing"]]
// 1. Provide a name ('Pivot Layout')
// 2. Set 1 Column to be pivoted by AG Grid:
//    a. 'language'
// 3. Set Row Grouping on 2 Columns: 
//    a. 'license' 
//    b. 'has_wiki'
// 4. Provide  Aggregations for 2 Columns
//    a.  git_hub_stars - sum
//    b.  github_watchers - count
// 5. Define Column Widths on the 2 Aggregated Columns
//    a.  github_watchers - 100 pixels
//    b.  github_stars - 475 pixels
const initialState: InitialState = {
  Layout: {
    CurrentLayout: 'Pivot Layout',
    Layouts: [
    {
      Name: 'Pivot Layout',
      PivotColumns: ['language'],
      PivotGroupedColumns: ['license', 'has_wiki'],
      RowGroupValues: {
        RowGroupDefaultBehavior: 'always-expanded',
      },
      PivotAggregationColumns: [
      {
        ColumnId: 'github_watchers',
        AggFunc: 'count',
      },
      {
        ColumnId: 'github_stars',
        AggFunc: 'sum',
      },
      ],
      ColumnSizing: {
        github_watchers: {Width: 475},
        github_stars: {Width: 200},
      },
    }],
  },
}
```

## Aggregation-Only Layouts

Typically Pivot Layouts include one or more "Pivot Columns" and AG Grid creates a dynamic Pivot Result column for each unique permutation of Pivot Column value and Aggregation Column.

However it is possible to create Pivot Layouts that **only contain Aggregated Columns** (and no Pivot Columns).

When this happens AG Grid will still create a Pivot Result Column for each Aggregation Column but no Pivot Column Groups.

When defining an Aggregation-only Pivot Layout, provide an **empty array** for the mandatory `pivotColumns` property

### Defining an Aggregation Only Pivot Layout

Choose something unique but relevant.

This is how AdapTable will refer to the Layout in the UI

As you do not require Pivot Columns, **provide an empty array**.

Provide Columns to be row-grouped using the `PivotGroupedColumns` property

Define the Aggregations to display using the `PivotAggregationColumns` property.

```ts [[1, 9, "Name"],[2, 10, "PivotColumns"],[3, 11, "PivotGroupedColumns"],[4, 12, "PivotAggregationColumns"]]
// 1. Set no Pivot Columns
// 2. Set Row Grouping on license Column 
// 3. Provide  Aggregations for git_hub_stars and github_watchers Columns
const initialState: InitialState = {
  Layout: {
    CurrentLayout: 'Pivot Agg Only Layout',
    Layouts: [
    {
      Name: 'Pivot Agg Only Layout',
      PivotColumns: ['language'],
      PivotGroupedColumns: ['license', 'has_wiki'],
      PivotAggregationColumns: [
      {
        ColumnId: 'github_watchers',
        AggFunc: 'count',
      },
      {
        ColumnId: 'github_stars',
        AggFunc: 'sum',
      },
    ],
  },
}
```

**Example: Pivot Aggregation Layouts**

Pivot Layout with Agg Columns

 

- This example creates a Pivot Layout which contains:
  - **no** PivotColumns
  - 2 PivotAggregationColumns - `Github Stars` & `Github Stars` (with `ColumnSizing` set for both columns, and `SuppressAggFuncInHeader` set to *true*)
  - 1 PivotGroupedColumn - `Language`

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Pivoted Aggregation Layout',
  initialState: {
    Dashboard: {
      Tabs: [{Name: 'Demo', Toolbars: ['Layout']}],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Layout'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Pivot Agg Layout',
      Layouts: [
        {
          Name: 'Pivot Agg Layout',
          PivotGroupedColumns: ['language'],
          SuppressAggFuncInHeader: true,
          ColumnSizing: {
            github_watchers: {Width: 475},
            github_stars: {Width: 200},
          },
          PivotAggregationColumns: [
            {
              ColumnId: 'github_watchers',
              AggFunc: 'sum',
            },
            {
              ColumnId: 'github_stars',
              AggFunc: 'sum',
            },
          ],
          PivotColumns: [], // empty array required
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {ColDef, GridOptions, themeBalham} from 'ag-grid-enterprise';

import {rowData, WebFramework} from './rowData';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions<WebFramework> = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';

export const onAdaptableReady = ({agGridApi}: AdaptableReadyInfo) => {
  agGridApi.openToolPanel('columns');
};
```
