# Custom Export Destinations

Canonical page: https://www.adaptabletools.com/docs/handbook-exporting-destinations-custom

- AdapTable System Export Destinations can be supplemented by Custom Destinations provided by developers
- Custom Destinations can be provided by Developers in 2 ways:
  - an `onExport` function that is automatically invoked by AdapTable
  - an [Adaptable Form](https://www.adaptabletools.com/docs/ui-tutorial-configuring-adaptable-forms/index.md) when bespoke information is required by the runtime user prior to export

If the [System Export Destinations](https://www.adaptabletools.com/docs/handbook-exporting-destinations/index.md) provided by AdapTable are insufficient, developers can easily supply their own custom export destinations.

This is done via the `customDestinations` property in [Export Options](https://www.adaptabletools.com/docs/technical-reference-exporting/index.md).

The property returns a list (either directly or via a function) of which Custom Destinations are available.

### `customDestinations`

User-provided Report Destinations (used in addition to those shipped in AdapTable)

  [`CustomDestination[]`](https://www.adaptabletools.com/docs/reference/customdestination.md)

These are Export Destinations provided by developers at design-time.

The [`CustomDestination`](https://www.adaptabletools.com/docs/reference/customdestination.md) object is defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [form](https://www.adaptabletools.com/docs/reference/customdestination.md#form) | [`AdaptableForm`](https://www.adaptabletools.com/docs/reference/adaptableform.md)`<`[`ExportFormContext`](https://www.adaptabletools.com/docs/reference/exportformcontext.md)`>` | Optional Adaptable Form; if provided, it must include Buttons that will execute the Export |
| [name](https://www.adaptabletools.com/docs/reference/customdestination.md#name) | `string` | Name of Custom Destination (mandatory) |
| [onExport](https://www.adaptabletools.com/docs/reference/customdestination.md#onexport) | `(reportContext: `[`ReportContext`](https://www.adaptabletools.com/docs/reference/reportcontext.md)`) => void` | Optional Function invoked when Export is applied (used if no form is supplied) |

You can provide either an array of custom destinations, or provide a function which returns an array.

<b>Hard Coded List</b>

The simplest method is to return an array of the Custom Destinations you wish to be available:

```ts {3}
const adaptableOptions: AdaptableOptions = {
  exportOptions: {
    customDestinations: [
      {
        name: 'Destination 1', // in practice more props will be provided
      },
      {
        name: 'Destination 2', // in practice more props will be provided
      },
    ],
  },
};
```

<b>Via a Function</b>

Alternatively, you can provide a function which returns the Custom Destinations.

The function receives context of type [`CustomDestinationsContext`](https://www.adaptabletools.com/docs/reference/customdestinationscontext.md) defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [currentLayoutName](https://www.adaptabletools.com/docs/reference/customdestinationscontext.md#currentlayoutname) | `string` | Name of current Layout |
| [currentReportFormat](https://www.adaptabletools.com/docs/reference/customdestinationscontext.md#currentreportformat) | [`ReportFormatType`](https://www.adaptabletools.com/docs/reference/reportformattype.md) | Format of current Report |
| [currentReportName](https://www.adaptabletools.com/docs/reference/customdestinationscontext.md#currentreportname) | [`ReportNameType`](https://www.adaptabletools.com/docs/reference/reportnametype.md) | Name of current Report |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/customdestinationscontext.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |

```ts {4}
// Return just 1 Custom Destination for Current Layout Report
const adaptableOptions: AdaptableOptions = {
  exportOptions: {
    customDestinations: (context: CustomDestinationsContext) => {
      return context.currentReportName == 'Current Layout'
        ? [
            {
              name: 'Destination 1', // in practice more props will be provided
            },
          ]
        : [
            {
              name: 'Destination 1', // in practice more props will be provided
            },
            {
              name: 'Destination 2', // in practice more props will be provided
            },
          ];
    },
  },
};
```

- This allows you to export grid data to email, PDF, REST Apis and other locations you require
- And you can still leverage AdapTable's Reports, Expressions, Scheduling and State Management functionality

## Defining a Custom Destination

The Custom Destination object is defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [form](https://www.adaptabletools.com/docs/reference/customdestination.md#form) | [`AdaptableForm`](https://www.adaptabletools.com/docs/reference/adaptableform.md)`<`[`ExportFormContext`](https://www.adaptabletools.com/docs/reference/exportformcontext.md)`>` | Optional Adaptable Form; if provided, it must include Buttons that will execute the Export |
| [name](https://www.adaptabletools.com/docs/reference/customdestination.md#name) | `string` | Name of Custom Destination (mandatory) |
| [onExport](https://www.adaptabletools.com/docs/reference/customdestination.md#onexport) | `(reportContext: `[`ReportContext`](https://www.adaptabletools.com/docs/reference/reportcontext.md)`) => void` | Optional Function invoked when Export is applied (used if no form is supplied) |

As can be seen, it has a mandatory `name` property, and depending on the complexity required, there are 2 (mutually exclusive) ways of providing the Custom Destination implementation:

- an `onExport` function that is invoked by AdapTable automatically
- an [Adaptable Form](https://www.adaptabletools.com/docs/ui-tutorial-configuring-adaptable-forms/index.md) if bespoke information is required by the runtime user prior to export

### Using an `onExport` function

In this use case, the developer needs to provide an implementation for the `onExport` function.

This function will then be invoked by AdapTable whenever a report is exported to the Custom Destination.

### Using the onExport function

The `onExport` function receives a `reportContext` object (containing all the report data required) and returns void:

```tsx
onExport: (reportContext: ReportContext) => void;
```

The [`ReportContext`](https://www.adaptabletools.com/docs/reference/reportcontext.md) object is defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [reportData](https://www.adaptabletools.com/docs/reference/reportcontext.md#reportdata) | [`ExportResultData`](https://www.adaptabletools.com/docs/reference/exportresultdata.md) | Export Data for the Report |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/reportcontext.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |

The `reportData` property is of type [`ReportData`](https://www.adaptabletools.com/docs/reference/reportdata.md) which contains all the data being exported:

| Property | Type | Description |
| --- | --- | --- |
| [columns](https://www.adaptabletools.com/docs/reference/reportdata.md#columns) | [`ReportColumn`](https://www.adaptabletools.com/docs/reference/reportcolumn.md)`[]` | Columns in the Report |
| [groupColumnIds](https://www.adaptabletools.com/docs/reference/reportdata.md#groupcolumnids) | `string[]` | Group columns IDs in the Report |
| [pivotColumnIds](https://www.adaptabletools.com/docs/reference/reportdata.md#pivotcolumnids) | `string[]` | Pivot columns IDs in the Report |
| [rows](https://www.adaptabletools.com/docs/reference/reportdata.md#rows) | `Record<string, any>[]` | Row Data in the Report |

The `ReportContext` object itself derives from [`BaseExportContext`](https://www.adaptabletools.com/docs/reference/baseexportcontext.md) which is defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [exportDestination](https://www.adaptabletools.com/docs/reference/baseexportcontext.md#exportdestination) | [`ExportDestinationType`](https://www.adaptabletools.com/docs/reference/exportdestinationtype.md) | Export Destination for the Report |
| [report](https://www.adaptabletools.com/docs/reference/baseexportcontext.md#report) | [`Report`](https://www.adaptabletools.com/docs/reference/report.md) | The Report Configuration being run |
| [reportFormat](https://www.adaptabletools.com/docs/reference/baseexportcontext.md#reportformat) | [`ReportFormatType`](https://www.adaptabletools.com/docs/reference/reportformattype.md) | Format of the Report being run |
| [reportName](https://www.adaptabletools.com/docs/reference/baseexportcontext.md#reportname) | [`ReportNameType`](https://www.adaptabletools.com/docs/reference/reportnametype.md) | Name of the Report being run |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/baseexportcontext.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |

**Example: Custom Export Destination via Function**

Custom Export Destination: via a Function

- This example contains a Custom Export Destination - `Rest Endpoint`
- It provides an implementation for the `onExport` function, that is invoked when the Report runs
- Note: the demo simply sends a [System Status](https://www.adaptabletools.com/docs/ui-tutorial-using-toast-notifications/index.md) message with the Report's name (and console logs its data), but a "real world" application's implementation would send the data to a REST endpoint

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  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 {ExportResultData} from '@adaptabletools/adaptable/src/AdaptableOptions/ExportOptions';
import {AdaptableOptions, ReportContext} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Export Destination: Function',
  exportOptions: {
    customDestinations: [
      {
        name: 'REST Endpoint',
        onExport: (reportContext: ReportContext) => {
          const reportData: ExportResultData = reportContext.reportData;
          const header: string =
            'Sending to REST - Report: "' + reportContext.report.Name;
          reportContext.adaptableApi.systemStatusApi.setInfoSystemStatus(
            header
          );
          console.log('Report data:', reportData);
        },
      },
    ],
  },

  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Demo',
          Toolbars: ['Export', 'SystemStatus'],
        },
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Export', 'SystemStatus'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Export: {
      CurrentReport: 'All Data',
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_projects',
            'has_pages',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

### Defining an AdapTable Form

It might sometimes be necessary for users to provide **additional** information regarding the custom destination e.g. an email address.

This is done by including an [Adaptable Form](https://www.adaptabletools.com/docs/ui-tutorial-configuring-adaptable-forms/index.md) definition in the Custom Destination.

AdapTable will read this form definition metadata and display the form dynamically (including default values).

See [Guide to defining an Adaptable Form](https://www.adaptabletools.com/docs/ui-tutorial-configuring-adaptable-forms/index.md) for full details

The form can include as many field definitions as required, together with optional default values if needed.

For the form to be effective it must include a **Submit Button** with an `onClick` property that performs the Export.

- When providing a form AdapTable will **not** perform the Export automatically
- It is your responsibility to provide a button with an `onClick` function which will export the data

### Providing an AdapTable Form

The submit Button is an [Adaptable Button](https://www.adaptabletools.com/docs/ui-tutorial-displaying-adaptable-buttons/index.md) which has the usual disabled, hidden and onClick functions.

The Button can also be used to perform validation e.g. remain disabled until the form fields are all valid.

All the button's properties will receive as a parameter the [`ExportFormContext`](https://www.adaptabletools.com/docs/reference/exportformcontext.md) object which is defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [customDestination](https://www.adaptabletools.com/docs/reference/exportformcontext.md#customdestination) | [`CustomDestination`](https://www.adaptabletools.com/docs/reference/customdestination.md) | Custom Export destination |
| [report](https://www.adaptabletools.com/docs/reference/exportformcontext.md#report) | [`Report`](https://www.adaptabletools.com/docs/reference/report.md) | The exported report |
| [reportData](https://www.adaptabletools.com/docs/reference/exportformcontext.md#reportdata) | [`ExportResultData`](https://www.adaptabletools.com/docs/reference/exportresultdata.md) | The data in the report |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/exportformcontext.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |

The [`ReportData`](https://www.adaptabletools.com/docs/reference/reportdata.md) object comprises multiple properties which contain all the data being exported:

| Property | Type | Description |
| --- | --- | --- |
| [columns](https://www.adaptabletools.com/docs/reference/reportdata.md#columns) | [`ReportColumn`](https://www.adaptabletools.com/docs/reference/reportcolumn.md)`[]` | Columns in the Report |
| [groupColumnIds](https://www.adaptabletools.com/docs/reference/reportdata.md#groupcolumnids) | `string[]` | Group columns IDs in the Report |
| [pivotColumnIds](https://www.adaptabletools.com/docs/reference/reportdata.md#pivotcolumnids) | `string[]` | Pivot columns IDs in the Report |
| [rows](https://www.adaptabletools.com/docs/reference/reportdata.md#rows) | `Record<string, any>[]` | Row Data in the Report |

See the [Adaptable Button Tutorial](https://www.adaptabletools.com/docs/ui-tutorial-displaying-adaptable-buttons/index.md) for further information on configuring Buttons

- Custom Destination can also be included in a [Scheduled Export](https://www.adaptabletools.com/docs/handbook-exporting-scheduling/index.md)
- The same dynamic form and its associated form fields and buttons will be displayed in the Schedule Wizard

**Example: Custom Export Destination via a Form**

Custom Export Destination: via a Form

- This example contains a Custom Export Destination - `Email` which uses an [Adaptable Form](https://www.adaptabletools.com/docs/ui-tutorial-configuring-adaptable-forms/index.md) that displays automatically when the Export is invoked
- The Form contains a number of input fields:
  - Dropdown with pre-selected _Email Addresses_
  - Textboxes for _Subject_ (pre-populated) and _Body_
  - Checkbox for _Including Headers_
- The Form also contains validation - the `Export` button cannot be clicked if the Email Body input is blank
- The `onClick` property of the `Export` Button simply sends the data as a [System Status](https://www.adaptabletools.com/docs/ui-tutorial-using-toast-notifications/index.md) (but a real world example will be different)
- We also removed all System Export Destinations so that **only** the Custom Destination is available

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  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 {
  AdaptableButton,
  AdaptableOptions,
  ExportFormContext,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Export Destination: Form',
  exportOptions: {
    customDestinations: [
      {
        name: 'Email',
        form: {
          title: 'Email Settings',
          description: 'Provide email details',
          fields: [
            {
              name: 'emailAddress',
              label: 'Email Address',
              fieldType: 'select',
              options: [
                {
                  value: 'support@adaptabletools.com',
                  label: 'Support',
                },
                {
                  value: 'sales@adaptabletools.com',
                  label: 'Sales',
                },
              ],
              defaultValue: 'support@adaptabletools.com',
            },
            {
              name: 'emailSubject',
              label: 'Email Subject',
              fieldType: 'text',
              defaultValue: 'AdapTable Report Data',
            },
            {
              name: 'emailBody',
              label: 'Email Body',
              fieldType: 'text',
            },
            {
              name: 'includeHeaders',
              label: 'Include Headers',
              fieldType: 'checkbox',
            },
          ],
          buttons: [
            {
              label: 'Cancel',
            },
            {
              label: 'Export',
              buttonStyle: {
                tone: 'success',
                variant: 'raised',
              },
              disabled: (
                button: AdaptableButton<ExportFormContext>,
                context: ExportFormContext
              ) => {
                const subject: any = context.formData?.['emailSubject'];
                const body: any = context.formData?.['emailBody'];
                return subject == '' || body == '';
              },
              onClick: (
                button: AdaptableButton<ExportFormContext>,
                context: ExportFormContext
              ) => {
                // send the report to an email address
                // the context contains the report data
                const message = `Sending to Email: Report: "${context.report.Name}"
                  with format: ${context.reportData.type} to ${context.formData?.['emailAddress']}`;

                const info = `Report contains: Columns: ${context.report.ReportColumnScope}, Rows: ${context.report.ReportRowScope}`;

                context.adaptableApi.systemStatusApi.setSuccessSystemStatus(
                  message,
                  info
                );
              },
            },
          ],
        },
      },
    ],
    systemExportDestinations: [],
  },

  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Demo',
          Toolbars: ['Export', 'SystemStatus'],
        },
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Export', 'SystemStatus'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Export: {
      CurrentReport: 'All Data',
      CurrentFormat: 'Excel',
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_projects',
            'has_pages',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```
