- Data Grid docs
- Rows and records
Editing
Edit cells in place with typed editors, field rules, calculated fields, the fill handle, added and removed records, paste, undo and redo, locally or through your server.
An editable grid works like a small data-entry app: people type into cells, pick values from lists and dates from a calendar, paste ranges from a spreadsheet, drag the fill handle, add and remove records and undo their mistakes, while field rules keep the data valid. Local data is edited in a private copy in the Worker; a server source sends each change to your server, which decides.
Open the edit example: order entry with field rules and a Region list
In the grid
| Action | How |
|---|---|
| Edit a cell | Double-click it, press F2 or Enter, or start typing |
| Save and move | Enter saves and moves down, Tab saves and moves sideways |
| Cancel | Escape |
| Edit the whole record | Shift+Enter opens the record dialog |
| Undo, redo | Ctrl+Z, Ctrl+Y or Ctrl+Shift+Z (Cmd on a Mac), or the header buttons |
| Fill down | Select a range and press Ctrl+D: the top row's values fill the rows below |
| Fill a series | Drag the square handle at the corner of the selected range (see Fill handle) |
| Tick a box | Click a boolean cell's box, or press Space on it |
| Paste | Ctrl+V pastes tab-separated text from the focused cell; the record dialog's Paste rows pastes several records |
| Add, remove | Add record in the toolbar; Remove record in the record dialog |
| Calculated field | Calculated field in the toolbar adds a column such as [@Units]*[@Price] |
A value a rule rejects keeps the editor open with the reason, so nothing invalid is saved. Each field edits with the control that suits it; see Editors.
Editors
A field chooses its control with editor, or gets one from its type and its options. The same controls appear in the cell, in the record details dialog and in the Add record dialog.
editor | Default for | What the user gets |
|---|---|---|
'text' | other fields | A text input |
'number' | type: 'number' | A text input with a decimal keyboard on phones |
'date' | type: 'date' | A date picker; typing a character starts a typed date instead |
'checkbox' | type: 'boolean' | A box in the cell itself: click it or press Space to flip it |
'select' | a field with options | A text input that suggests the options as the user types and refuses a value outside them |
'multiselect' | A list of check boxes under the cell; the value is the chosen options joined by ", " ("Go, SQL") | |
'textarea' | Several lines of text; Alt+Enter adds a line, Enter saves |
options lists the values a field takes, as strings or numbers. A select suggests them, a multiselect lists them, and getFields() reports them in each field's options. The items of a list rule (see Field rules) count as options too, so such a field also edits with a select.
const fields = [
{ name: 'Region', type: 'string', options: ['East', 'West', 'North', 'South'] }, // a select
{ name: 'Skills', type: 'string', editor: 'multiselect', options: ['Go', 'Rust', 'SQL'] },
{ name: 'Started', type: 'date' }, // a date picker
{ name: 'Remote', type: 'boolean' }, // a check box
{ name: 'Notes', type: 'string', editor: 'textarea' },
];
Open the tree example to try a select, a multiselect, a date picker and check boxes in one grid.
Fill handle
In an editable grid on local records, the selected range has a small square handle at its corner, when every column of the range can be edited. Dragging it down, up or sideways over the drawn records fills the cells it passes, as a spreadsheet does:
- numbers and dates continue by their step: 1, 2 gives 3, 4; 5 Jan, 12 Jan gives 19 Jan;
- known lists continue: Monday, Tuesday gives Wednesday; Jan gives Feb;
- text that ends in a number counts on: "Item 1" gives "Item 2";
- everything else is copied.
The whole fill is one change and one undo step, and it goes through beforeEdit and the field rules like any edit. Ctrl+D and fillDown() still copy the range's first record into the records below it.
Turn it on
editable: true: the grid starts editable.allowEdit: true: the grid starts read-only with an Edit copy button, whichenableEditing()presses from code. Edits stay in that copy until the user exports it.isEditable()says whether edits are accepted now, andgetSource().dirtywhether the copy was changed.- The
changeevent (onChange) reports every change:{ action: 'edit', cells },paste,{ action: 'add', records, ids },{ action: 'remove', ids },undo,redo,{ action: 'formula', name, formula },{ action: 'move', ids, before }(moved records) or{ action: 'transaction', … }(live data), each withsource: 'user'or'api'. Use it to save, or to mark the page as changed.
Field rules
Each field in fields can carry rules:
| Rule | Effect |
|---|---|
readOnly: true | Can't be edited |
required: true | Can't be left blank |
validator | { type, operator, min, max, items, message }, as Excel's data validation |
formula | A calculated field, recalculated when its inputs change, never typed into |
Validator types: list (items), whole, decimal (or number), date, time, textLength and custom (a formula that must be true). Operators: between, notBetween, equal, notEqual, greaterThan, lessThan, greaterThanOrEqual, lessThanOrEqual; without one, min and max are the bounds. message is what the user sees. errorStyle: 'warning' or 'information' lets the value through.
JavaScript
import { mountTable } from '@8sheets/data-grid';
const fields = [
{ name: 'Order', type: 'number', format: '0', readOnly: true },
{ name: 'Customer', type: 'string', required: true },
{ name: 'Region', type: 'string', options: ['East', 'West', 'North', 'South'] }, // edited with a select
{ name: 'Units', type: 'number', required: true, validator: { type: 'whole', operator: 'between', min: 1, max: 500, message: 'Units must be a whole number from 1 to 500.' } },
{ name: 'Price', type: 'number', format: '#,##0.00' },
{ name: 'Revenue', type: 'number', format: '#,##0.00', formula: '[@Units]*[@Price]' },
];
let dirty = false;
const grid = await mountTable(document.querySelector('#orders'), {
title: 'Order entry',
fields,
data: orders,
editable: true,
onChange: (change) => {
dirty = true;
console.log(change.action, change);
},
});
// Save: export the edited records as a file, or send them to your server.
document.querySelector('#save').addEventListener('click', async () => {
const csv = await grid.exportResults('csv');
await fetch('/api/orders/import', { method: 'POST', body: csv });
dirty = false;
});React
import { useMemo, useRef, useState } from 'react';
import { DataGrid } from '@8sheets/data-grid-react';
const fields = [
{ name: 'Order', type: 'number', format: '0', readOnly: true },
{ name: 'Customer', type: 'string', required: true },
{ name: 'Units', type: 'number', required: true, validator: { type: 'whole', operator: 'between', min: 1, max: 500, message: 'Units must be a whole number from 1 to 500.' } },
{ name: 'Price', type: 'number', format: '#,##0.00' },
{ name: 'Revenue', type: 'number', format: '#,##0.00', formula: '[@Units]*[@Price]' },
];
export function OrderEntry({ orders }) {
const ref = useRef(null);
const [dirty, setDirty] = useState(false);
const options = useMemo(() => ({ title: 'Order entry', fields, data: orders, editable: true }), [orders]);
async function save() {
const csv = await ref.current.exportResults('csv');
await fetch('/api/orders/import', { method: 'POST', body: csv });
setDirty(false);
}
return (
<>
<button disabled={!dirty} onClick={save}>Save</button>
<div style={{ height: 480 }}>
<DataGrid ref={ref} options={options} onChange={() => setDirty(true)} />
</div>
</>
);
}Vue
<script setup>
import { computed, ref } from 'vue';
import { DataGrid, useDataGrid } from '@8sheets/data-grid-vue';
const props = defineProps({ orders: Array });
const fields = [
{ name: 'Order', type: 'number', format: '0', readOnly: true },
{ name: 'Customer', type: 'string', required: true },
{ name: 'Units', type: 'number', required: true, validator: { type: 'whole', operator: 'between', min: 1, max: 500, message: 'Units must be a whole number from 1 to 500.' } },
{ name: 'Price', type: 'number', format: '#,##0.00' },
{ name: 'Revenue', type: 'number', format: '#,##0.00', formula: '[@Units]*[@Price]' },
];
const options = computed(() => ({ title: 'Order entry', fields, data: props.orders, editable: true }));
const { dataGrid } = useDataGrid();
const dirty = ref(false);
async function save() {
const csv = await dataGrid.value.exportResults('csv');
await fetch('/api/orders/import', { method: 'POST', body: csv });
dirty.value = false;
}
</script>
<template>
<button :disabled="!dirty" @click="save">Save</button>
<div style="height: 480px"><DataGrid ref="dataGrid" :options="options" @change="dirty = true" /></div>
</template>Angular
import { Component, Input, ViewChild } from '@angular/core';
import { DataGridComponent, DataGridOptions } from '@8sheets/data-grid-angular';
@Component({
selector: 'app-order-entry',
imports: [DataGridComponent],
template: `
<button [disabled]="!dirty" (click)="save()">Save</button>
<eight-data-grid #grid [options]="options" (gridChange)="dirty = true" style="height: 480px" />`,
})
export class OrderEntry {
@ViewChild('grid') grid!: DataGridComponent;
dirty = false;
options: DataGridOptions = {};
@Input() set orders(data: Record<string, unknown>[]) {
this.options = {
title: 'Order entry',
data,
editable: true,
fields: [
{ name: 'Order', type: 'number', format: '0', readOnly: true },
{ name: 'Customer', type: 'string', required: true },
{ name: 'Units', type: 'number', required: true, validator: { type: 'whole', operator: 'between', min: 1, max: 500, message: 'Units must be a whole number from 1 to 500.' } },
{ name: 'Price', type: 'number', format: '#,##0.00' },
{ name: 'Revenue', type: 'number', format: '#,##0.00', formula: '[@Units]*[@Price]' },
],
};
}
async save() {
const csv = await this.grid.exportResults('csv');
await fetch('/api/orders/import', { method: 'POST', body: csv });
this.dirty = false;
}
}From code
Everything the user can do, your code can do, and it goes through the same rules and events:
| Method | Does |
|---|---|
setCellValue(id, field, value) | Stores one value; resolves false when a beforeEdit handler cancelled it, rejects when a rule refuses it |
updateRecords([{ id, values }]) | Stores several values as one change and one undo step |
addRecords(records) | Adds records, resolves with their IDs (local copy) |
removeRecords(ids) | Removes records as one undo step (local copy) |
paste(text or rows, { id, field, repeat }) | Pastes tab-separated text from a cell rightwards and down |
fillDown() | Copies the range's first record into the records below it, as Ctrl+D |
applyTransaction({ add, update, remove }) | Applies the application's own changes without undo; see Live data |
undo(), redo(), canUndo(), canRedo() | History of a local copy |
startEdit(id, field, { text }), stopEdit({ cancel }), getEditingCell() | Open, close and read the cell editor |
addCalculatedField(name, formula) | Adds a calculated field to a local copy |
Before a change is applied, beforeEdit, beforeAdd, beforeRemove or beforePaste fires. A handler cancels it with e.preventDefault() (or by returning false), and a beforeEdit handler may also change cells[i].value to store something else. editStart (cancellable) and editEnd follow the cell editor.
JavaScript
import { mountTable } from '@8sheets/data-grid';
const grid = await mountTable(document.querySelector('#orders'), {
title: 'Order entry',
fields,
data: orders,
editable: true,
// Business rules the field rules can't express, for the user's edits and the API's alike.
onBeforeEdit: (e) => {
for (const cell of e.cells) {
if (cell.field === 'Customer') cell.value = String(cell.value ?? '').trim(); // store it trimmed
if (cell.field === 'Units' && Number(cell.value) > stockLeft()) e.preventDefault();
}
},
onBeforeRemove: (e) => {
if (!confirm(`Remove ${e.ids.length} orders?`)) e.preventDefault();
},
onChange: (change) => console.log(change.action, change.source),
});
const [id] = await grid.addRecords([{ Customer: 'Acme Ltd', Region: 'East', Units: 5, Price: 24 }]);
await grid.setCellValue(id, 'Units', 6);
undoButton.onclick = () => grid.undo();
grid.on('change', () => (undoButton.disabled = !grid.canUndo()));React
import { useMemo, useRef, useState } from 'react';
import { DataGrid } from '@8sheets/data-grid-react';
export function OrderEntry({ orders, fields }) {
const ref = useRef(null);
const [canUndo, setCanUndo] = useState(false);
const options = useMemo(() => ({ title: 'Order entry', fields, data: orders, editable: true }), [orders, fields]);
return (
<>
<button onClick={() => ref.current.addRecords([{ Customer: 'New customer', Units: 1 }])}>Add order</button>
<button disabled={!canUndo} onClick={() => ref.current.undo()}>Undo</button>
<div style={{ height: 480 }}>
<DataGrid
ref={ref}
options={options}
onBeforeEdit={(e) => {
if (e.cells.some((c) => c.field === 'Units' && Number(c.value) > 500)) e.preventDefault();
}}
onChange={() => setCanUndo(ref.current.canUndo())}
/>
</div>
</>
);
}Vue
<script setup>
import { computed, ref } from 'vue';
import { DataGrid } from '@8sheets/data-grid-vue';
const props = defineProps({ orders: Array, fields: Array });
const options = computed(() => ({ title: 'Order entry', fields: props.fields, data: props.orders, editable: true }));
const dataGrid = ref(null);
const canUndo = ref(false);
// Through Vue's emit, cancel with preventDefault(); returning false doesn't reach the grid.
function checkUnits(e) {
if (e.cells.some((c) => c.field === 'Units' && Number(c.value) > 500)) e.preventDefault();
}
</script>
<template>
<button @click="dataGrid.addRecords([{ Customer: 'New customer', Units: 1 }])">Add order</button>
<button :disabled="!canUndo" @click="dataGrid.undo()">Undo</button>
<div style="height: 480px">
<DataGrid ref="dataGrid" :options="options" @before-edit="checkUnits" @change="canUndo = dataGrid.canUndo()" />
</div>
</template>Angular
import { Component, Input, ViewChild } from '@angular/core';
import { DataGridComponent, DataGridOptions } from '@8sheets/data-grid-angular';
@Component({
selector: 'app-order-entry',
imports: [DataGridComponent],
template: `
<button (click)="grid.addRecords([{ Customer: 'New customer', Units: 1 }])">Add order</button>
<button [disabled]="!canUndo" (click)="grid.undo()">Undo</button>
<eight-data-grid #grid [options]="options" (beforeEdit)="checkUnits($event)" (gridChange)="canUndo = grid.canUndo()" style="height: 480px" />`,
})
export class OrderEntry {
@Input() options: DataGridOptions = {};
@ViewChild('grid') grid!: DataGridComponent;
canUndo = false;
checkUnits(e: { cells: { field: string; value: unknown }[]; preventDefault(): void }) {
if (e.cells.some((c) => c.field === 'Units' && Number(c.value) > 500)) e.preventDefault();
}
}Calculated fields
A field with formula is computed from the same record, with Excel's structured references: [@Units]*[@Price], IF([@Status]="Paid",0,[@Due]), TEXT([@Date],"yyyy-mm"). It recalculates when a field it uses changes, and it can be sorted, filtered, grouped and totalled like any other. Calculated field in the toolbar adds one while the grid is editable, and so does addCalculatedField('Total', '=[@Units]*[@Price]'); the change event reports it as { action: 'formula', name, formula }.
Edit server data
With a server source, edits go to your server in batches:
- Pass
editable: true, give the source anupdatemethod (updateUrlinremoteTableSource), and seteditable: trueon each field the user may change. - Each page carries a
revisionof the dataset. An update sends{ state, revision, cells: [{ id, field, value }] }. - The server checks the revision and the user's rights, applies the whole batch or nothing, and returns the new
{ revision }. A stale revision gets HTTP 409, and the user sees "The data changed. Reopen the record before editing."
tableQueryService(table, { editableFields: ['Units', 'Price'] }) in the source download implements this contract.
Limits
- A server source takes edits and pastes through
update. Adding and removing records, fill down, the fill handle, calculated fields and undo need local data. - Local edits live in the grid's memory: export, or read them back through
onChange, before the page closes. - The fill handle fills over drawn records; to fill further, select a larger range and use Ctrl+D, or paste.
- A multiselect stores its choices as one text value joined by ", ", not as an array.