# Updating Grid Cells

Canonical page: https://www.adaptabletools.com/docs/handbook-managing-grid-data-cells

- AdapTable provides 2 methods in Grid API used to set specific cell values

The [`Grid API`](https://www.adaptabletools.com/docs/reference/gridapi.md) section of [Adaptable API](https://www.adaptabletools.com/docs/technical-reference-adaptable-api/index.md) contains 2 functions for when just particular cells, rather than a whole row, needs to be updated.

- We strongly recommend **using these functions** to update cells, rather than calling `setDataValue` on an AG Grid RowNode directly
- Each function ultimately calls AG Grid but first performs AdapTable checks and publishes the [Cell Changed Event](https://www.adaptabletools.com/docs/handbook-managing-grid-data-changed-events/index.md)

- See [Updating Grid Rows](https://www.adaptabletools.com/docs/handbook-managing-grid-data-rows-update/index.md) for instructions on how to update entire rows
- See the [Editing Data](https://www.adaptabletools.com/docs/handbook-editing/index.md) section for details on the many AdapTable Modules that support data entry and editing

- `setCellValue` - updates a single Cell in the Grid 
- `setCellValues` - calls `setCellValue` in a loop

Many [Modules](https://www.adaptabletools.com/docs/technical-reference-adaptable-modules/index.md) in AdapTable react to this function being invoked, including:
- causing [Cell or Row Flashing](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md) if configured
- triggering any [Data Change Alerts](https://www.adaptabletools.com/docs/handbook-alerting/index.md) and apply any [Validation Alerts](https://www.adaptabletools.com/docs/handbook-alerting-validation/index.md)
- firing the [Cell Changed Event](https://www.adaptabletools.com/docs/technical-reference-editing/index.md)
- populating the [Data Change History Monitor](https://www.adaptabletools.com/docs/handbook-monitoring-data-change-history/index.md) with details of the edit

These functions are used by AdapTable for cell edits triggered by [Smart Edit](https://www.adaptabletools.com/docs/handbook-editing-smart-edit/index.md), [Bulk Update](https://www.adaptabletools.com/docs/handbook-editing-bulk-update/index.md), [Shortcuts](https://www.adaptabletools.com/docs/handbook-editing-shortcut/index.md) or [Plus Minus](https://www.adaptabletools.com/docs/handbook-editing-plus-minus/index.md)

### `setCellValue`

Update a Single Cell in AG Grid

Use this function to update a single Cell in AG Grid.

The function signature is as follows: 

```ts
setCellValue(cellUpdateRequest: CellUpdateRequest): void;
```

As can be seen it is a void function that receives a [`CellUpdateRequest`](https://www.adaptabletools.com/docs/reference/cellupdaterequest.md) object defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [columnId](https://www.adaptabletools.com/docs/reference/cellupdaterequest.md#columnid) | `string` | Id of Column in which edited cell is situated |
| [newValue](https://www.adaptabletools.com/docs/reference/cellupdaterequest.md#newvalue) | `any` | New Value for the cell |
| [primaryKeyValue](https://www.adaptabletools.com/docs/reference/cellupdaterequest.md#primarykeyvalue) | `any` | Primary Key column&#39;s value in row - how Adaptable locates the cell |
| [rowNode](https://www.adaptabletools.com/docs/reference/cellupdaterequest.md#rownode) | `IRowNode<TData>` | AG Grid Row Node that contains the cell (optional) |

```ts {14}
// Get the node to update
const rowNode: RowNode = context.rowNode

// Get Primary Key Value
const primaryKeyValue = adaptableApi.gridApi.getPrimaryKeyValueForRowNode(rowNode)

// Increment the Github Stars column in the row
const cellUpdateRequest: CellUpdateRequest = {
  columnId: 'github_stars',
  newValue: rowNode.data.github_stars + increment,
  primaryKeyValue: primaryKeyValue,
  rowNode: rowNode,
};
adaptableApi.gridApi.setCellValue(cellUpdateRequest);
``` 

### `setCellValues`

Update multiple Cells in AG Grid

Use this function to update several Cells in one call. It invokes `setCellValue` for each [`CellUpdateRequest`](https://www.adaptabletools.com/docs/reference/cellupdaterequest.md) in the array.

```ts
setCellValues(cellUpdateRequests: CellUpdateRequest[]): void;
```

```ts
const cellUpdateRequests: CellUpdateRequest[] = otherLicenseNodes.map(rowNode => ({
  columnId: 'license',
  newValue: 'Unknown License',
  primaryKeyValue: adaptableApi.gridApi.getPrimaryKeyValueForRowNode(rowNode),
  rowNode,
}));
adaptableApi.gridApi.setCellValues(cellUpdateRequests);
```

**Example: Setting Cell Values**

Using Grid API to set individual cell values

- This demo provides examples of updating individual Cell Values via the `setCellValue` function in [`Grid API`](https://www.adaptabletools.com/docs/reference/gridapi.md) (using 3 Custom Toolbar Buttons):
  - First button updates `Language` in first row to Python
  - Second button increments the `Github Stars` value in the second row
  - Third button changes all rows that have a License of 'Other' to 'Unknown License' (using the `setCellValues` function)

- Click the 3 buttons in turn to see the cell changes made (we turned on [Cell Flashing](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md) to make it easier to see)
- Open the Data Change History Monitor to see a record of the changes

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,
  CellUpdateRequest,
  CustomToolbarButtonContext,
  GridApi,
} from '@adaptabletools/adaptable';
import {IRowNode} from 'ag-grid-enterprise';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Setting Cell Values',
  dashboardOptions: {
    customToolbars: [
      {
        name: 'ButtonToolbar',
        title: 'Buttons',
        toolbarButtons: [
          {
            label: 'Set Lang to Python (1st Row)',
            onClick: (
              button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              // Get handle to Grid APi
              const gridApi: GridApi = context.adaptableApi.gridApi;
              // Get the first Row Node
              const firstNode = gridApi.getFirstRowNode();
              if (firstNode) {
                const cellUpdateRequest: CellUpdateRequest = {
                  columnId: 'language',
                  newValue: 'Python',
                  primaryKeyValue:
                    gridApi.getPrimaryKeyValueForRowNode(firstNode),
                  rowNode: firstNode,
                };
                gridApi.setCellValue(cellUpdateRequest);
              }
            },
            buttonStyle: {
              tone: 'info',
              variant: 'text',
            },
          },
          {
            label: 'Increment Stars (2nd Row)',
            onClick: (
              button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              // Get handle to Grid APi
              const gridApi: GridApi = context.adaptableApi.gridApi;
              // Get the second Row Node
              const secondNode = gridApi.getRowNodeForIndex(1);
              if (secondNode) {
                const starsColumnId = 'github_stars';
                const currentStarsValue: number =
                  gridApi.getNormalisedValueFromRowNode(
                    secondNode,
                    starsColumnId
                  );

                const cellUpdateRequest: CellUpdateRequest = {
                  columnId: starsColumnId,
                  newValue: currentStarsValue + 1,
                  primaryKeyValue:
                    gridApi.getPrimaryKeyValueForRowNode(secondNode),
                  rowNode: secondNode,
                };
                gridApi.setCellValue(cellUpdateRequest);
              }
            },
            buttonStyle: {
              tone: 'success',
              variant: 'text',
            },
          },
          {
            label: 'Update "Other" Licences (2 Rows)',
            onClick: (
              button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              const gridApi: GridApi = context.adaptableApi.gridApi;
              const licenseColumnId = 'license';
              const nodes = gridApi.getAllRowNodes().filter((n: IRowNode) => {
                return n.data['license'] == 'Other';
              });
              let cellUpdateRequests: CellUpdateRequest[] = [];
              nodes.forEach((node: IRowNode) => {
                cellUpdateRequests.push({
                  columnId: licenseColumnId,
                  newValue: 'Unknown License',
                  primaryKeyValue: gridApi.getPrimaryKeyValueForRowNode(node),
                  rowNode: node,
                });
              });
              gridApi.setCellValues(cellUpdateRequests);
            },
            buttonStyle: {
              tone: 'warning',
              variant: 'text',
            },
          },
        ],
      },
    ],
  },
  dataChangeHistoryOptions: {
    activeByDefault: true,
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Demo',
          Toolbars: ['ButtonToolbar', 'DataChangeHistory'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'created_at',
            'has_wiki',
            'github_watchers',
            'updated_at',
            'pushed_at',
            'description',
            'open_issues_count',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
    FlashingCell: {
      FlashingCellDefinitions: [
        {
          Name: 'Flashing_Cell_Any_Change',
          Rule: 'ANY_CHANGE()',
          Scope: {
            All: true,
          },
        },
      ],
    },
  },
};
```
