# Configuring Free Text Columns

Canonical page: https://www.adaptabletools.com/docs/handbook-freetext-column-configuring

- Free Text Columns can be defined at design-time using Free Text Column Initial State
- The Free Text Column API can be used to add values programmatically at run-time

Free Text Columns are defined in `initialState.FreeTextColumn.FreeTextColumns` — see [Free Text Column Initial Adaptable State](https://www.adaptabletools.com/docs/technical-reference-freetext-column/index.md) and [`FreeTextColumn`](https://www.adaptabletools.com/docs/reference/freetextcolumn.md).

| Part of `FreeTextColumn` | Purpose |
| ------------------------ | ------- |
| `ColumnId` | Id used in Layouts, filters, and API |
| `FriendlyName` | Header text in the UI (optional) |
| `FreeTextColumnSettings` | **Required** `DataType`; layout flags (`Filterable`, `Sortable`, …); optional `CellDataType` |
| `DefaultValue` | Shown in every cell until the user overrides |
| `FreeTextStoredValues` | Per-row values keyed by `PrimaryKey` |

Run-time updates use [`FreeTextColumnApi.setStoredValues`](https://www.adaptabletools.com/docs/reference/freetextcolumnapi.md#setstoredvalues) (below).

## Defining Free Text Columns

### Defining a Free Text Column

There are (up to) 6 properties that you need to provide:

This value is used to refer to the Column in State

This value is used to refer to the Column in AdapTable UI

Whether the Column is `Text` `Number` `Date` or `Boolean`

Is only mandatory property in `FreeTextColumnSettings`

AdapTable provides an appropriate Cell Editor based on the DataType provided here

Used in each cell unless explicitly overridden by the User

Initial values to show in the column.

Each is keyed against the Primary Key value for the Row.

Provide additional settings for the Column (e.g. filterable, pivotable, resizable, sortable etc.)

```ts [[1, 5, "ColumnId"], [1, 17, "ColumnId"], [1, 27, "ColumnId"], [2, 6, "FriendlyName"], [2, 18, "FriendlyName"], [2, 28, "FriendlyName"], [3, 13, "DataType"], [3, 21, "DataType"], [3, 31, "DataType"], [4, 19, "DefaultValue"], [4, 29, "DefaultValue"], [5, 7, "FreeTextStoredValues"], [6, 12, "Resizable"], [6, 22, "Sortable"], [6, 32, "Filterable"]]
const initialState: InitialState = {
  FreeTextColumn: {
    FreeTextColumns: [
      {
        ColumnId: 'comments',
        FriendlyName: 'Ops Note',
        FreeTextStoredValues: [
          { PrimaryKey: 24195339, FreeText: 'Used by US team' },
          { PrimaryKey: 82095231, FreeText: 'Required by Support' },
        ],
        FreeTextColumnSettings: {
          Resizable: true,
          DataType: 'text',
        },
      },
      {
        ColumnId: 'orderCode',
        FriendlyName: 'Order Code',
        DefaultValue: 123,
        FreeTextColumnSettings: {
          DataType: 'number',
          Sortable: false,
          SuppressMenu: true,
        },
      },
      {
        ColumnId: 'isUsed',
        FriendlyName: 'Is Used',
        DefaultValue: false,
        FreeTextColumnSettings: {
          DataType: 'boolean',
          Filterable: true,
        },
      },
    ],
  },
};
```

- To prevent filtering on Free Text Columns, set `enableFilterOnSpecialColumns` to *false* in [Column Filter Options](https://www.adaptabletools.com/docs/technical-reference-filter/index.md)
- This will also disallow filtering on **all** [Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) and [Action Columns](https://www.adaptabletools.com/docs/handbook-action-column/index.md)

## Adding Values Programmatically

A commonly used function in Free Text Column API is `setStoredValues` which allows you to update values stored in Free Text Columns programmatically.

### `setStoredValues`

Adds Stored Values to a FreeText Column

This is a useful function that allows you to add values to a FreeText Column programmatically.

The definition is:

```js
  setStoredValues(
    columnId: string,
    storedValues: FreeTextStoredValue[],
    replaceAction: 'All' | 'Conflicting' | 'None'
  ): void;
```

The `replaceAction` parameter defines the rules for how the new Stored Values should interact with any existing (and potentially clashing) cell values in the Column.

The property can be one of 3 values with the following behaviour for each:

- `All` - replaces **all** existing Stored Values for the Column with the new ones even if provided cells are currently empty
- `Conflicting` - adds all given stored values and replaces any existing ones which clash with the new set
- `None` - skips primary keys that already have a Stored Value; only adds entries for keys that are not yet present

```ts
// Replace all Existing Free Text Values in the Column with the 2 provided:
const values: FreeTextStoredValue[] = [
  {PrimaryKey: 5, FreeText: 'Fifth'},
  {PrimaryKey: 6, FreeText: 'Sixth'},
];
api.freeTextColumnApi.setStoredValues('OpsNote', values, 'All');
```

**Example: Adding FreeText Values via API**

Calling `setStoredValues` from Custom Toolbar buttons

- The demo starts with 3 stored values in the `OpsNote` Free Text column (`adaptableOptions.ts`)
- Each toolbar button applies the same payload : update `Angular` (PK `24195339`), and add `React` (PK `10270250`) - with a different `replaceAction`:
  - **None** — only adds the new Stored Value; existing ones are left unchanged
  - **Conflicting** — updates the overlapping Stored Value and adds the new one; other Stored Values remain
  - **All** — replaces **every** Stored Value with just the payload
- Use **Reset** to restore the initial 3 Stored Values (`replaceAction: 'All'`)

Click **None**, then **Reset**, and compare with **Conflicting** and **All**

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,
  CustomToolbarButtonContext,
  FreeTextStoredValue,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

const COLUMN_ID = 'OpsNote';

const initialStoredValues: FreeTextStoredValue[] = [
  {PrimaryKey: 24195339, FreeText: 'Used by the US team'},
  {PrimaryKey: 224663696, FreeText: 'My personal favourite'},
  {PrimaryKey: 82095231, FreeText: 'Required by Support Team'},
];

/** One conflicting PK (24195339) plus one new PK (10270250) */
const apiStoredValues: FreeTextStoredValue[] = [
  {PrimaryKey: 24195339, FreeText: 'Updated by API'},
  {PrimaryKey: 10270250, FreeText: 'Added by API'},
];

function setOpsNoteValues(
  context: CustomToolbarButtonContext,
  replaceAction: 'All' | 'Conflicting' | 'None'
) {
  context.adaptableApi.freeTextColumnApi.setStoredValues(
    COLUMN_ID,
    apiStoredValues,
    replaceAction
  );
}

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'FreeText Column API',
  dashboardOptions: {
    customToolbars: [
      {
        name: 'FreeTextApi',
        title: 'Set Stored Values',
        toolbarButtons: [
          {
            label: 'None',
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => setOpsNoteValues(context, 'None'),
            buttonStyle: {tone: 'neutral', variant: 'outlined'},
          },
          {
            label: 'Conflicting',
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => setOpsNoteValues(context, 'Conflicting'),
            buttonStyle: {tone: 'info', variant: 'outlined'},
          },
          {
            label: 'All',
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => setOpsNoteValues(context, 'All'),
            buttonStyle: {tone: 'success', variant: 'outlined'},
          },
          {
            label: 'Reset',
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              context.adaptableApi.freeTextColumnApi.setStoredValues(
                COLUMN_ID,
                initialStoredValues,
                'All'
              );
            },
            buttonStyle: {tone: 'error', variant: 'text'},
          },
        ],
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Demo',
          Toolbars: ['FreeTextApi'],
        },
      ],
    },
    FreeTextColumn: {
      FreeTextColumns: [
        {
          ColumnId: COLUMN_ID,
          FriendlyName: 'Ops Note',
          FreeTextStoredValues: initialStoredValues,
          FreeTextColumnSettings: {DataType: 'text', Resizable: true},
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'OpsNote',
            'language',
            'license',
            'github_stars',
            'github_watchers',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

## AG Grid Column Definitions

Typically Free Text Columns are provided only in Initial Adaptable State and not also defined in Grid Options.

However sometimes it is required to define the Free Text Column in AG Grid - e.g. if you want to show an AG Grid tooltip on the cell value.

This is possible by specifying a [Column Type](https://www.adaptabletools.com/docs/dev-guide-columns-column-types/index.md) of `freeTextColumn` in the AG Grid Column Definition.

Make sure `ColId` in the Column Definition and `ColumnId` in the Custom Column definition are the same value

See [Adding Special Column Types](https://www.adaptabletools.com/docs/dev-guide-columns-column-types/index.md) for more details and an accompanying demo

### AG Grid Cell Data Type

AG Grid provides a [Cell Data Type](https://www.adaptabletools.com/docs/dev-guide-aggrid-cell-data-types/index.md) (`cellDataType`) property which can be attached to one, or more, columns.

AdapTable allows users to leverage, and assign, an _application-registered_ AG Grid Cell Data Type when creating a Free Text Column.

- The `baseDataType` (or `extendsDataType`) must be compatible with the Free Text Column's AdapTable `DataType`
- If this is not provided then AdapTable will use the Free Text Column's `DataType` property

This is done via the optional `CellDataType` property in `FreeTextColumnSettings`:

- The key benefit is the Free Text Column automatically inherits everything the registered Cell Data Type provides
- e.g. its `valueFormatter`, `valueParser` and cell editor

```tsx {6}
{
  ColumnId: 'TargetPrice',
  FriendlyName: 'Target Price',
  FreeTextColumnSettings: {
    DataType: 'number', // AdapTable uses `number` for AQL, filtering and menus...
    CellDataType: 'pricing', // ...but AG Grid renders the cell using the registered `pricing` type
  },
},
```

**Example: Free Text Columns: AG Grid Cell Data Type**

Free Text Columns: Using an AG Grid Cell Data Type

- This demo registers 2 custom AG Grid Cell Data Types in `dataTypeDefinitions` (in AG Grid GridOptions), each with its own `valueFormatter`:
  - `currency` - formats a number as a USD currency value
  - `percentage` - formats a number (0-1) as a percentage
- It then defines 2 Free Text Columns which have an AdapTable `DataType` of `number` but a different `CellDataType`:
  - `Target Price` - an editable currency value (with 3 initial Stored Values)
  - `Completion` - an editable percentage value (defaulting to 50%)
- Because the AdapTable `DataType` is still `number`, both columns filter, sort and edit as numbers

- Edit a cell in the `Target Price` Column - you enter a plain number but it displays as currency
- Look at `gridOptions.ts` to see how the `currency` and `percentage` Cell Data Types are registered

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]
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, FreeTextStoredValue} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

const targetPriceValues: FreeTextStoredValue[] = [
  {PrimaryKey: 24195339, FreeText: 250000},
  {PrimaryKey: 224663696, FreeText: 1200000},
  {PrimaryKey: 82095231, FreeText: 90000},
];

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'FreeText Column Cell Data Type',
  initialState: {
    Theme: {CurrentTheme: 'dark'},
    FreeTextColumn: {
      FreeTextColumns: [
        {
          ColumnId: 'TargetPrice',
          FriendlyName: 'Target Price',
          FreeTextStoredValues: targetPriceValues,
          FreeTextColumnSettings: {
            // AdapTable uses `number` for AQL, filtering and menus...
            DataType: 'number',
            // ...but AG Grid renders (and edits) the cell using the `currency` type
            CellDataType: 'currency',
          },
        },
        {
          ColumnId: 'Completion',
          FriendlyName: 'Completion',
          DefaultValue: 0.5,
          FreeTextColumnSettings: {
            DataType: 'number',
            CellDataType: 'percentage',
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'TargetPrice',
            'Completion',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham, ValueFormatterLiteParams} 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,
  // Application-registered AG Grid Cell Data Types.
  // A Free Text Column can reference these via `CellDataType`.
  dataTypeDefinitions: {
    currency: {
      baseDataType: 'number',
      extendsDataType: 'number',
      valueFormatter: (params: ValueFormatterLiteParams<WebFramework, number>) =>
        params.value == null
          ? ''
          : params.value.toLocaleString('en-US', {
              style: 'currency',
              currency: 'USD',
              maximumFractionDigits: 0,
            }),
    },
    percentage: {
      baseDataType: 'number',
      extendsDataType: 'number',
      valueFormatter: (params: ValueFormatterLiteParams<WebFramework, number>) =>
        params.value == null ? '' : `${(params.value * 100).toFixed(0)}%`,
    },
  },
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```
