Data sources
Every grid has exactly one data source, attached like any other module. The source decides the mode:
- client — all rows are in the browser; search, sort, filters and paging run in memory (Turkish-aware collation and accent-folding search included).
- server — the server pages, sorts and searches; the grid sends a query per change, keeps only the current page and lets the latest request win (earlier ones are aborted).
| Source | Mode | Typical use |
|---|---|---|
data: rows (shorthand) / arraySource(rows) | client | rows you already have |
DOM source (automatic) / domSource() | client | a server-rendered <tbody> |
fetchAll({ url, dataSrc, method, csrf, body }) | client | one JSON request, then local search/sort/paging |
serverSide({ url, protocol, … }) | server | large lists; see Server protocols |
customSource({ mode, load }) | either | anything else |
If you attach no source, the grid uses data when given, otherwise the DOM source when the table already has body rows, otherwise an empty array.
Chaining works too
new Datagrid(el, { columns }).use(serverSide(...)) replaces the default source the grid picked, as long as no source was given explicitly. A second explicit source throws DG008.
Arrays
new Datagrid("#agents", { label: "Agents", columns, data: rows });
// same as: use: [arraySource(rows)]Change the rows later without re-creating the grid:
| Method | Effect |
|---|---|
grid.setData(rows) | replace every row |
grid.addRows(rows, { keepPage }) | append (jumps to the last page unless keepPage); ignored on a server source |
grid.removeRow(key) | remove by row key |
grid.refreshRow(key, row?) | re-render one row (optionally with a new object) |
DOM (progressive enhancement)
Give the grid a table that already has rows and nothing else. <thead> becomes the column list and the existing <tr> elements are adopted, not re-created: cell HTML, links, inputs and event listeners survive. Search, sort and paging run in the browser.
import { Datagrid } from "@akinozgen17/datagrids";
// no columns, no data: <thead> becomes the columns, the existing <tr>s are adopted
const init = () => new Datagrid("#guide-dom", { pageSize: 5 });
init();
document.querySelector("#guide-dom-destroy").addEventListener("click", () => {
Datagrid.get("#guide-dom")?.destroy(); // the original table is back, byte for byte
});
document.querySelector("#guide-dom-init").addEventListener("click", () => {
if (!Datagrid.get("#guide-dom")) init(); // get() returns null; it never creates a grid
});<div class="demo-buttons">
<button type="button" id="guide-dom-destroy">destroy()</button>
<button type="button" id="guide-dom-init">new Datagrid()</button>
</div>
<table id="guide-dom">
<caption>Unit inventory</caption>
<thead>
<tr>
<th data-dg-key="code">Code</th>
<th data-dg-key="item">Item</th>
<th data-dg-key="qty" data-dg-type="number">Qty</th>
<th data-dg-key="place">Place</th>
<th data-dg-key="note" data-dg-sortable="false">Note</th>
</tr>
</thead>
<tbody>
<tr id="inv-1"><td><span class="dg-id">INV-001</span></td><td>Green Herb</td><td data-order="42">42</td><td>Spencer Mansion</td><td><b>Critical</b> stock</td></tr>
<tr id="inv-2"><td><span class="dg-id">INV-002</span></td><td>Red Herb</td><td data-order="7">7</td><td>Raccoon City</td><td>—</td></tr>
<tr id="inv-3"><td><span class="dg-id">INV-003</span></td><td>Ink Ribbon</td><td data-order="120">120</td><td>R.P.D.</td><td><a href="#inv-3">Record</a></td></tr>
<tr id="inv-4"><td><span class="dg-id">INV-004</span></td><td>First Aid Spray</td><td data-order="15">15</td><td>Light Tower</td><td>Shelf 3</td></tr>
<tr id="inv-5"><td><span class="dg-id">INV-005</span></td><td>Blue Herb</td><td data-order="3">3</td><td>Arklay Mountains</td><td>—</td></tr>
<tr id="inv-6"><td><span class="dg-id">INV-006</span></td><td>Umbrella badge</td><td data-order="1">1</td><td>NEST</td><td><i>Evidence</i></td></tr>
<tr id="inv-7"><td><span class="dg-id">INV-007</span></td><td>Playing card</td><td data-order="2">2</td><td>Spencer Mansion</td><td>—</td></tr>
<tr id="inv-8"><td><span class="dg-id">INV-008</span></td><td>Flashlight</td><td data-order="11">11</td><td>Rockfort Island</td><td>No battery</td></tr>
</tbody>
</table>Header attributes refine each column:
Attribute on <th> | Effect |
|---|---|
data-dg-key="qty" | column key (default: a slug of the header text) |
data-dg-type="number" / "money" | numeric sorting, end alignment |
data-dg-sortable="false" | not sortable |
data-dg-searchable="false" | not searched |
data-dg-visible="false" | starts hidden |
data-dg-hideable="false" | locked in the column menu |
data-dg-export="false" | left out of exports |
data-dg-align="end" / "center" | alignment |
On cells, data-order="42" gives the value used for sorting and searching instead of the visible text; a row's id becomes its key. destroy() puts every adopted row back, attributes included.
To initialize tables declaratively (<table data-datagrid="name">), see Lifecycle → upgrade().
Fetch once
fetchAll loads one JSON document and then works in client mode — good for lists of a few thousand rows that should feel instant.
import { Datagrid, column, fetchAll } from "@akinozgen17/datagrids";
import { statusLabels, statusTones } from "./data.js";
// one GET, then search / sort / paging happen in the browser
new Datagrid("#guide-fetchall", {
label: "Agents (fetched once)",
pageSize: 5,
columns: [
column.text("name", { title: "Name" }),
column.text("unit", { title: "Unit" }),
column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }),
column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }),
],
use: [fetchAll({ url: "/api/all/agents?limit=200" })],
});<table id="guide-fetchall"></table>| Option | Default | Description |
|---|---|---|
url | — | endpoint |
method | "GET" ("POST" with body) | |
dataSrc | data key, or the body itself when it is an array | path or (json) => rows |
csrf | configure().csrf | send X-CSRF-TOKEN from <meta name="csrf-token"> |
body | — | JSON body |
reload() fetches again.
Server
import { serverSide, yajra } from "@akinozgen17/datagrids";
use: [serverSide({ url: "/agents/data", protocol: yajra(), csrf: true })]The transport (fetch, abort, timeout, CSRF, Laravel headers, error normalization) is shared; the protocol decides the wire format. Three ship with the library — the classic SSP wire (ssp(), and its yajra() preset), Laravel's paginator JSON (laravelPaginator()) and the datagrids protocol (dgp()). See Server protocols.
Custom sources
customSource takes a mode and a load(query, ctx) function and returns { rows, total, filtered, hasMore?, meta? }. In server mode you receive the neutral query for the current page; in client mode return every row once.
import { Datagrid, column, customSource } from "@akinozgen17/datagrids";
import { agents } from "./data.js";
const all = agents(300);
// a server-mode source: you receive the neutral query and return one page
const source = customSource({
mode: "server",
async load(query, { signal }) {
await new Promise((r) => setTimeout(r, 200)); // pretend this is GraphQL / IndexedDB / a worker
if (signal.aborted) throw new DOMException("aborted", "AbortError");
let rows = all.filter((r) => r.name.toLowerCase().includes(query.search.toLowerCase()));
const [s] = query.sort;
if (s) rows = [...rows].sort((a, b) => (a[s.key] > b[s.key] ? 1 : -1) * (s.dir === "asc" ? 1 : -1));
const start = (query.page - 1) * query.pageSize;
return { rows: rows.slice(start, start + query.pageSize), total: all.length, filtered: rows.length };
},
});
new Datagrid("#guide-custom", {
label: "Custom source",
pageSize: 5,
columns: [column.text("ref", { title: "Ref" }), column.text("name", { title: "Name" }), column.text("place", { title: "Place" })],
use: [source],
});<table id="guide-custom"></table>Throw (or reject with) an object shaped like { kind, status, message, retryable } to show the error state; honor ctx.signal so superseded loads stop early.
Row keys
Selection, row actions, refreshRow and focus keeping need a stable key per row. The grid uses, in order: the rowKey option (a field name or (row) => string), row.id, row.DT_RowId. Without any of them it falls back to the row index and prints DG003.
new Datagrid("#agents", { columns, data, rowKey: "uuid" });Related
- Server protocols
- Lifecycle — load modes, reload, destroy
- Grid options