table2 paging, sort and live filter htmx

table() with the htmx option: sort headers, a live filter and a pager or a "Load more" row, answered as fragments of the same URL.

Options

OptionMeaning
htmx => true | [...]On table($data, ['htmx' => ...]) or ->htmx([...]): id, sort, filter, pager (pages, more, infinite), delay, tiebreak, push_url, url... (see table()->htmx()).

Example

Name Stock
Lemon 16
Mango 3
Orange 10
Peach 17

Code

$rows = [];
foreach (['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig', 'Grape', 'Kiwi', 'Lemon', 'Mango', 'Orange', 'Peach'] as $i => $name) {
    $rows[$i + 1] = ['id' => $i + 1, 'name' => $name, 'stock' => ($i * 7) % 20];
}
return table($rows, ['pager_records_on_page' => 4, 'filter_params' => ['name' => 'like']])
    ->htmx(['id' => 'docs-ref-hx-table', 'pager' => 'more', 'filter' => ['name'], 'sort' => ['name', 'stock']])
    ->text('name')
    ->text('stock');

Notes

  • The box div.yf-table2-htmx is the target; an htmx request whose HX-Target is the box (or its "load more" row) gets the box alone through _result(), every other request the page, with Vary set (partial responses).
  • Sort keys are whitelisted, the live filter accepts only conditions that escape their value; the address bar follows (hx-push-url), so Back and bookmarks keep the state; without JavaScript headers and pager are links.
  • Accessibility: aria-sort on the sorted header, focus kept on the control after a swap, labelled filter fields.

Bootstrap 3 and 5

Bootstrap 3 form-inline / input-sm; Bootstrap 5 form-control-sm / btn-outline-secondary; both follow the dark colour mode.

See also: table/htmx, demo:table/htmx, demo:htmx/table