# Master Detail Grids

Canonical page: https://www.adaptabletools.com/docs/handbook-master-detail

- AdapTable fully supports the Master / Detail mode provided by [AG Grid](https://www.ag-grid.com/javascript-data-grid/master-detail/)
- It provides a dedicated [Plugin](https://www.adaptabletools.com/docs/technical-reference-plugins/index.md) which extends the functionality on offer

One of the most powerful features in AG Grid are [Master Detail Grids](https://www.ag-grid.com/javascript-data-grid/master-detail/).

These are grids where each row in the `Master` Grid can be expanded to display a `Details` grid.

AdapTable fully supports (and extends) AG Grid Master Detail grids.

It does so via a dedicated [Plugin](https://www.adaptabletools.com/docs/technical-reference-plugins/index.md) which provides extra features.

Primarily it enables all Detail Grids to share common AdapTable objects (e.g. [Reports](https://www.adaptabletools.com/docs/handbook-exporting/index.md) or [Format Columns](https://www.adaptabletools.com/docs/handbook-column-formatting/index.md)).

## Installing Master Detail Plugin

npm install @adaptabletools/adaptable-plugin-master-detail-aggrid

- If [using CommonJS](https://www.adaptabletools.com/docs/getting-started-installation/index.md#esm-and-cjs-formats), then install `@adaptabletools/adaptable-plugin-master-detail-aggrid-cjs` instead
- Make sure also to include your [License Key](https://www.adaptabletools.com/docs/getting-started-license-key/index.md) in the `DetailOptions` grid you provide

Unlike with [Row Grouping](https://www.adaptabletools.com/docs/handbook-grouping-rows/index.md), the Details Grid is a totally separate, fully configurable AdapTable instance.

Each Details Grid contains its own set of columns and own unique data

This allows you essentially to provide 2 definitions:

- the main **Master** Grid which provides the top level of rows
- the **Details** Grid which will appear when a Master row is expanded

### Providing Details Grid Definition

The Details Grid is provided in the `detailAdaptableOptions` property in Master Detail Plugin Options and is added to the plugins section of [Adaptable Options](https://www.adaptabletools.com/docs/technical-reference-adaptable-options/index.md).

```ts
plugins: [
  masterDetailAgGridPlugin({
    detailAdaptableOptions: {
      // provide here - including adaptableId
    },
  }),
],
```

It is possible to create a second Master / Detail grid as the child of an initial Master / Details grid.

Only one level of nesting Master / Details grids is possible

When the Master Grid is row grouped, a Layout with `RowGroupDefaultBehavior: 'always-expanded'` (see [Expanding Row Groups](https://www.adaptabletools.com/docs/handbook-grouping-rows-expanded-collapsed/index.md)) and `gridApi.expandAllRowGroups()` expand the Row Groups only, not the Master rows

**Example: Master Detail**

Using the Master Detail Plugin

- This demo illustrates how to use Master Detail Grids in AdapTable
- The Master and Detail grids have different AdapTable configurations
- However each Detail Grids shares the same [Column Formatting](https://www.adaptabletools.com/docs/handbook-column-formatting/index.md) on the `GitHub Stars` column
### Expand to see how the Master Detail Grid was configured

The Detail Grids are defined in the `masterDetailAgGridPlugin` setction of `plugins`: 
Note: this includes Initial Adaptable State which includes the Format Column on the `GitHub Stars` column
```ts
plugins: [
  masterDetailAgGridPlugin({
    detailAdaptableOptions: {
      adaptableId: 'Language Details',
      primaryKey: 'id',
      initialState: {
        FormatColumn: {
          FormatColumns: [
            {
              Name: 'FormatColumn-github_stars-212',
              Scope: {
                ColumnIds: ['github_stars'],
              },
              Style: {
                FontWeight: 'Bold',
                BackColor: '#ffbc05',
              },
            },
          ],
        },
      },
    },
  }),
],
```

- Create a Format Column in one Details Grid and see it applied in the other 2

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  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template] + @adaptabletools/adaptable-plugin-master-detail-aggrid
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, DetailInitContext} from '@adaptabletools/adaptable';
import masterDetailAgGridPlugin from '@adaptabletools/adaptable-plugin-master-detail-aggrid';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Master Detail',
  plugins: [
    masterDetailAgGridPlugin({
      detailAdaptableOptions: {
        adaptableId: 'Language Details',
        primaryKey: 'id',
        initialState: {
          Theme: {CurrentTheme: 'dark'},
          FormatColumn: {
            FormatColumns: [
              {
                Name: 'formatColumn-github_stars',
                Scope: {
                  ColumnIds: ['github_stars'],
                },
                Style: {
                  FontWeight: 'Bold',
                  BackColor: '#ffbc05',
                },
              },
            ],
          },
          Layout: {
            CurrentLayout: 'Details Layout',
            Layouts: [
              {
                TableColumns: [
                  'name',
                  'language',
                  'has_wiki',
                  'pushed_at',
                  'github_stars',
                  'open_issues_count',
                  'github_watchers',
                  'updated_at',
                  'description',
                  'created_at',
                ],
                Name: 'Details Layout',
                AutoSizeColumns: true,
              },
            ],
          },
        },
      },
    }),
  ],
  initialState: {
    Dashboard: {
      ModuleButtons: ['FormatColumn'],
    },
    Theme: {CurrentTheme: 'dark'},
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-language',
          Scope: {
            ColumnIds: ['language'],
          },
          Style: {
            ForeColor: '#2966a8',
            FontWeight: 'Bold',
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Master Layout',
      Layouts: [
        {
          TableColumns: [
            'language',
            'year',
            'author',
            'version',
            'maintainer',
            'fileExtension',
          ],
          Name: 'Master Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

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

import {rowData as detailRowData} from './rowData';
import {columnDefs as detailsColumnDefs} from './columnDefs';

const rowData = [
  {
    id: 1,
    language: 'TypeScript',
    year: 2012,
    author: 'Anders Hejlsberg',
    version: '4.5.5',
    maintainer: 'Microsoft',
    fileExtension: '.ts',
  },
  {
    id: 2,
    language: 'JavaScript',
    year: 1995,
    author: 'Brendan Eich',
    version: 'ES 2015',
    maintainer: 'ECMA',
    fileExtension: '.js',
  },
  {
    id: 3,
    language: 'HTML',
    year: 1993,
    author: 'Tim Berners-Lee',
    version: '5.2',
    maintainer: 'W3C',
    fileExtension: '.html',
  },
];

const columnDefs = [
  {
    field: 'language',
    cellRenderer: 'agGroupCellRenderer',
  },
  {
    field: 'year',
  },
  {
    field: 'version',
  },
  {
    field: 'author',
  },
  {
    field: 'maintainer',
  },
  {
    field: 'fileExtension',
  },
];

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    enableRowGroup: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  masterDetail: true,

  detailCellRendererParams: {
    detailGridOptions: {
      columnDefs: detailsColumnDefs,
      sideBar: true,
    },

    getDetailRowData(params: any) {
      const language = params.data.language;
      const details = detailRowData.filter(
        details => details.language === language
      );

      if (details) {
        setTimeout(() => {
          // simulate async call
          params?.successCallback?.(details);
        }, 1000);
      }
    },
  },
};
```

## Initialising the Details Grid

AdapTable provides an `onDetailInit` property.

This contains a function that is invoked when a Details Grid is initialised.

You can use this property to provide bespoke configuration for the Details Grid at run-time

### onDetailInit property

The `onDetailInit` property is exposed by Master Detail Plugin Options.

This takes the form of a function which is invoked when each Detail Grid initialises.

It receives the [`DetailInitContext`](https://www.adaptabletools.com/docs/reference/detailinitcontext.md) object which includes details of the Master Row Node (and its data) as well as the [Adaptable API](https://www.adaptabletools.com/docs/technical-reference-adaptable-api/index.md):

| Property | Type | Description |
| --- | --- | --- |
| [data](https://www.adaptabletools.com/docs/reference/detailinitcontext.md#data) | `IRowNode['data']` | The data in the Master Grid Row that was opened |
| [primaryKeyValue](https://www.adaptabletools.com/docs/reference/detailinitcontext.md#primarykeyvalue) | `unknown` | Primary Key Value of Master Grid Row that was opened |
| [rowNode](https://www.adaptabletools.com/docs/reference/detailinitcontext.md#rownode) | `IRowNode` | Row Node in the Master Grid that was opened |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/detailinitcontext.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |

**Example: Master Detail - Detail Init**

Initialising the Detail Grids

- This demo illustrates how to use `onDetailInit` to configure the Detail Grids in Master Detail Grids
- The function calls the AdapTable API to close the [Tool Panel](https://www.adaptabletools.com/docs/ui-tool-panel/index.md) (SideBar) in the Details Grid when it opens - but only if the `Language` is "JavaScript" or "TypeScript"
### Expand to see how onDetailInit was used

```ts
onDetailInit(detailContext: DetailInitContext) {
  const detailAdapTableApi: AdaptableApi = detailContext.adaptableApi;
  console.log('detail instance created', detailAdapTableApi);
  detailAdapTableApi.eventApi.on('AdaptableReady', () =>
    console.log('detail grid ready')
  );
  detailAdapTableApi.toolPanelApi.closeAdapTableToolPanel()
},
```

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  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template] + @adaptabletools/adaptable-plugin-master-detail-aggrid
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,
  DetailInitContext,
  AdaptableApi,
} from '@adaptabletools/adaptable';
import masterDetailAgGridPlugin from '@adaptabletools/adaptable-plugin-master-detail-aggrid';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Master DetailInit',
  plugins: [
    masterDetailAgGridPlugin({
      detailAdaptableOptions: {
        adaptableId: 'Language Details Init',
        primaryKey: 'id',
        initialState: {
          Theme: {CurrentTheme: 'dark'},
          Layout: {
            CurrentLayout: 'Details Layout',
            Layouts: [
              {
                Name: 'Details Layout',
                TableColumns: [
                  'name',
                  'github_stars',
                  'language',
                  'github_watchers',
                  'updated_at',
                  'description',
                  'created_at',
                  'has_wiki',
                  'pushed_at',
                  'open_issues_count',
                ],
                AutoSizeColumns: true,
              },
            ],
          },
        },
      },
      onDetailInit(detailContext: DetailInitContext) {
        const detailAdapTableApi: AdaptableApi = detailContext.adaptableApi;
        detailAdapTableApi.eventApi.on('AdaptableReady', () =>
          console.log('detail grid ready')
        );
        if (
          detailContext.data['language'] === 'JavaScript' ||
          detailContext.data['language'] === 'TypeScript'
        ) {
          detailAdapTableApi.toolPanelApi.closeAdapTableToolPanel();
        }
      },
    }),
  ],
  initialState: {
    Dashboard: {
      ModuleButtons: ['FormatColumn'],
    },
    Theme: {CurrentTheme: 'dark'},
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-language',
          Scope: {
            ColumnIds: ['language'],
          },
          Style: {
            ForeColor: '#2966a8',
            FontWeight: 'Bold',
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Master Layout',
      Layouts: [
        {
          TableColumns: [
            'language',
            'year',
            'author',
            'version',
            'maintainer',
            'fileExtension',
          ],
          Name: 'Master Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

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

import {rowData as detailRowData} from './rowData';
import {columnDefs as detailsColumnDefs} from './columnDefs';

const rowData = [
  {
    id: 1,
    language: 'TypeScript',
    year: 2012,
    author: 'Anders Hejlsberg',
    version: '4.5.5',
    maintainer: 'Microsoft',
    fileExtension: '.ts',
  },
  {
    id: 2,
    language: 'JavaScript',
    year: 1995,
    author: 'Brendan Eich',
    version: 'ES 2015',
    maintainer: 'ECMA',
    fileExtension: '.js',
  },
  {
    id: 3,
    language: 'HTML',
    year: 1993,
    author: 'Tim Berners-Lee',
    version: '5.2',
    maintainer: 'W3C',
    fileExtension: '.html',
  },
];

const columnDefs = [
  {
    field: 'language',
    cellRenderer: 'agGroupCellRenderer',
  },
  {
    field: 'year',
  },
  {
    field: 'version',
  },
  {
    field: 'author',
  },
  {
    field: 'maintainer',
  },
  {
    field: 'fileExtension',
  },
];

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    enableRowGroup: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  masterDetail: true,

  detailCellRendererParams: {
    detailGridOptions: {
      columnDefs: detailsColumnDefs,
      sideBar: true,
    },

    getDetailRowData(params: any) {
      const language = params.data.language;
      const details = detailRowData.filter(
        details => details.language === language
      );

      if (details) {
        setTimeout(() => {
          // simulate async call
          params?.successCallback?.(details);
        }, 1000);
      }
    },
  },
};
```

## Exporting Detail Rows

By default, exporting a master–detail grid includes **master rows only**.

Detail grids are separate AdapTable instances and are not merged into the file automatically.

To export nested rows for each expanded master row, set `getDetailRows` in [Export Options](https://www.adaptabletools.com/docs/technical-reference-exporting/index.md).

### `getDetailRows`

Detail rows to include under each master row when exporting a master–detail grid

This applies only to **Excel**, **Visual Excel**, or **CSV** (not JSON).

The callback runs once per master row.

It receives [`GetDetailRowsContext`](https://www.adaptabletools.com/docs/reference/getdetailrowscontext.md) — master row data, the active report format, and helpers (`createCellHeader`, `createCellCsv`, `createCellExcel`) — and returns detail rows to nest under that master row in the export file.

Use the same detail data you load in AG Grid's `getDetailRowData` (or your own store). Return `undefined` to omit detail rows for a given master row.

```ts
getDetailRows?: (
  context: GetDetailRowsContext<TData>
) => CsvDetailRow[] | ExcelDetailRow[] | undefined;
```

```ts {4,5,6,7,8,9,10}
const adaptableOptions: AdaptableOptions = {
  exportOptions: {
    getDetailRows: context => {
      const details = loadDetailRowsForMaster(context.masterRowData);
      const headers = [
        context.createCellHeader(''),
        context.createCellHeader('Name'),
      ];
      // return ExcelDetailRow[] or CsvDetailRow[] using createCellExcel / createCellCsv
      return buildDetailExportRows(context, headers, details);
    },
  },
};
```

See [Configuring Export](https://www.adaptabletools.com/docs/handbook-exporting-configuring/index.md) for the full Export Options available

**Example: Master Detail — Export**

Exporting master rows with nested detail data

- Master rows list programming languages; expand a row to load frameworks for that language in the detail grid
- `getDetailRows` exports those frameworks under each master row when you run **Current Layout** to Excel or CSV

- Export **Current Layout** to Excel and open the file — each language row is followed by its framework detail rows

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  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template] + @adaptabletools/adaptable-plugin-master-detail-aggrid
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, GetDetailRowsContext} from '@adaptabletools/adaptable';
import masterDetailAgGridPlugin from '@adaptabletools/adaptable-plugin-master-detail-aggrid';
import {rowData, WebFramework} from './rowData';

interface LanguageMasterRow {
  id: number;
  language: string;
  year: number;
  author: string;
  version: string;
  maintainer: string;
  fileExtension: string;
}

export const adaptableOptions: AdaptableOptions<LanguageMasterRow> = {
  primaryKey: 'id',
  adaptableId: 'Master Detail Export',
  exportOptions: {
    getDetailRows: (context: GetDetailRowsContext<LanguageMasterRow>) => {
      const {masterRowData, reportFormat, createCellCsv, createCellExcel, createCellHeader} =
        context;
      const details: WebFramework[] = rowData.filter(
        framework => framework.language === masterRowData.language
      );

      const useExcel = reportFormat === 'Excel' || reportFormat === 'VisualExcel';
      if (useExcel) {
        const headerCells = [
          createCellHeader(''),
          createCellHeader('Name'),
          createCellHeader('GitHub Stars'),
          createCellHeader('Open Issues'),
        ];
        const detailExportRows = [
          {outlineLevel: 1, cells: headerCells},
          ...details.map(framework => ({
            outlineLevel: 1,
            cells: [
              createCellExcel('', 'String'),
              createCellExcel(framework.name, 'String'),
              createCellExcel(framework.github_stars, 'Number'),
              createCellExcel(framework.open_issues_count, 'Number'),
            ],
          })),
        ];
        return detailExportRows;
      }

      const csvHeaderRow = [
        createCellCsv(''),
        createCellCsv('Name'),
        createCellCsv('GitHub Stars'),
        createCellCsv('Open Issues'),
      ];
      const detailExportRows = [
        csvHeaderRow,
        ...details.map(framework => [
          createCellCsv(''),
          createCellCsv(framework.name),
          createCellCsv(framework.github_stars),
          createCellCsv(framework.open_issues_count),
        ]),
      ];
      return detailExportRows;
    },
  },
  plugins: [
    masterDetailAgGridPlugin({
      detailAdaptableOptions: {
        adaptableId: 'Language Details',
        primaryKey: 'id',
        initialState: {
          Layout: {
            CurrentLayout: 'Details Layout',
            Layouts: [
              {
                TableColumns: ['name', 'language', 'github_stars', 'open_issues_count'],
                Name: 'Details Layout',
                AutoSizeColumns: true,
              },
            ],
          },
        },
      },
    }),
  ],
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Demo',
          Toolbars: ['Export'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Export: {
      CurrentReport: 'Current Layout',
      CurrentFormat: 'Excel',
    },
    Layout: {
      CurrentLayout: 'Master Layout',
      Layouts: [
        {
          TableColumns: [
            'language',
            'year',
            'author',
            'version',
            'maintainer',
            'fileExtension',
          ],
          Name: 'Master Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

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

import {rowData as detailRowData} from './rowData';
import {columnDefs as detailsColumnDefs} from './columnDefs';

const rowData = [
  {
    id: 1,
    language: 'TypeScript',
    year: 2012,
    author: 'Anders Hejlsberg',
    version: '4.5.5',
    maintainer: 'Microsoft',
    fileExtension: '.ts',
  },
  {
    id: 2,
    language: 'JavaScript',
    year: 1995,
    author: 'Brendan Eich',
    version: 'ES 2015',
    maintainer: 'ECMA',
    fileExtension: '.js',
  },
  {
    id: 3,
    language: 'HTML',
    year: 1993,
    author: 'Tim Berners-Lee',
    version: '5.2',
    maintainer: 'W3C',
    fileExtension: '.html',
  },
];

const columnDefs: ColDef[] = [
  {
    field: 'language',
    cellRenderer: 'agGroupCellRenderer',
  },
  {field: 'year'},
  {field: 'version'},
  {field: 'author'},
  {field: 'maintainer'},
  {field: 'fileExtension'},
];

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    enableRowGroup: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs,
  rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  masterDetail: true,
  detailCellRendererParams: {
    detailGridOptions: {
      columnDefs: detailsColumnDefs,
      sideBar: true,
    },
    getDetailRowData(params: any) {
      const language = params.data.language;
      const details = detailRowData.filter(
        details => details.language === language
      );

      if (details) {
        setTimeout(() => {
          params?.successCallback?.(details);
        }, 500);
      }
    },
  },
};
```

## Master Detail Plugin Options

| Property | Type | Description |
| --- | --- | --- |
| [detailAdaptableOptions](https://www.adaptabletools.com/docs/reference/masterdetailpluginoptions.md#detailadaptableoptions) | [`AdaptableOptions`](https://www.adaptabletools.com/docs/reference/adaptableoptions.md) | `AdaptableOptions` used in Detail Grids; all share same behaviour &amp; State |
| [onDetailInit](https://www.adaptabletools.com/docs/reference/masterdetailpluginoptions.md#ondetailinit) | `(context: `[`DetailInitContext`](https://www.adaptabletools.com/docs/reference/detailinitcontext.md)`) => void` | Function called when a Detail Grid is initialised, receives context including Adaptable Api |

### FAQ

**Can I export master and detail rows in one file?**
Yes. Without `getDetailRows`, exports include master rows only. Implement `getDetailRows` in Export Options so detail data is nested under each master row in Excel or CSV exports (see [Exporting Detail Rows](#exporting-detail-rows)).

**Can I export a detail grid on its own?**
Yes — each detail grid is its own AdapTable instance and can be exported separately via the Export API if you obtain its Adaptable API (for example from `onDetailInit`).
