htmx() table()

Sort headers, a live filter and a pager or "load more" row that htmx swaps without reloading the page.

table()->htmx($options = [])

Options

OptionMeaning
idId of the swap box ([a-z][a-z0-9_-]*); default yf-table2-1, -2... per request.
sorttrue (default): text / link / date / stars columns; a list of keys or key => column; false: no sort headers.
filtertrue or a list of filter_params keys: a search field each above the table, sent while typing.
pagerpages (default), more (a "Load more" row) or infinite (it loads when scrolled into view).
delayDebounce of the live filter in ms; default 300.
tiebreakUnique column appended to the ORDER BY, so pages keep one order.
push_urlhx-push-url on headers, pager and filter; default true.
urlBase of the links (site code, a path from the root or an http(s) URL); default the request URI.
sort_param, dir_param, filter_paramQuery parameter names; default sort, dir, f.
filter_max_lengthLongest live filter value; default 100.

Example

Name Price
Elderberry 1.90
Fig 2.25
Grape 2.60
Kiwi 2.95

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, 'price' => number_format(0.5 + $i * 0.35, 2)];
}
return table($rows, ['pager_records_on_page' => 4, 'filter_params' => ['name' => 'like']])
    ->htmx(['id' => 'ref-fruits', 'sort' => ['name', 'price'], 'filter' => ['name']])
    ->text('name')
    ->text('price');

Notes

  • The same as the table option htmx; htmx(false) turns it off. Without the option the table prints what it printed before, byte for byte.
  • For an htmx request that targets the box, render() answers with the box alone through _class('htmx')->_result() and ends the request.
  • Sorting is whitelisted: ?sort= is looked up in the keys of sort only, the ORDER BY is built from the column name in backticks.
  • Without JavaScript the headers and the pager are links and the filter a GET form.

Bootstrap 3 and 5

Filter fields are input-sm / btn-default under Bootstrap 3 and form-control-sm / btn-outline-secondary under 5; the hidden labels use sr-only or visually-hidden.

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