modul-is / datagrid
Simple datagrid for Nette - Nette Database Selection as the source, rendered for Bootstrap 6
Requires
- php: ^8.4
- latte/latte: ^3.1
- modul-is/form: ^2.0
- nette/application: ^3.2
- nette/database: ^3.2
- nette/forms: ^3.3
- nette/utils: ^4.0
Requires (Dev)
- modul-is/coding-standard: ^5
- nette/bootstrap: ^3.2
- nette/di: ^3.2
- nette/http: ^3.3
- nette/tester: ^2.6
- phpstan/phpstan-nette: ^2
- tracy/tracy: ^2.10
Suggests
- nette/di: for configuration by ModulIS\Datagrid\DI\DatagridExtension
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-02 13:54:46 UTC
README
Simple datagrid for Nette - rows of a Nette Database Selection, rendered for Bootstrap 6, client side in plain
JavaScript (naja). Filters are controls of modul-is/form.
Features: columns (text, number, date, bool, dial, link, status), filters in the header of the columns or above the table (text, select, multiselect, date, date range, range), sorting, pagination, row actions with confirmation, toolbar buttons, group actions, CSV and custom exports, detail of a row, editable cells, remembered state.
Getting started
use ModulIS\Datagrid\Datagrid; use Nette\Database\Table\ActiveRow; protected function createComponentGrid(): Datagrid { $grid = new Datagrid($this->Explorer->table('user')); $grid->setDefaultSort(['lastname' => 'ASC']); $grid->addText('lastname', 'Příjmení') ->setSortable() ->setFilterText(); $grid->addText('insurance.name', 'Pojišťovna') // column of the referenced row ->setSortable() ->setFilterSelect($insurancePairs, 'insurance_id'); $grid->addText('insurance.company.name', 'Skupina') // over three tables - sorted and filtered by the same path ->setSortable() ->setFilterText(); $grid->addDateTime('created', 'Vytvořeno') ->setFormat('j. n. Y H:i') ->setFilterDateRange(); $grid->addAction(':Admin:User:edit') ->setIcon('edit') ->setTitle('Editovat') ->setColor('info'); $grid->addAction('delete!') // signal of the parent of the grid ->setIcon('trash') ->setColor('danger') ->setAjax() ->setConfirm('Smazat uživatele %s?', 'lastname') ->setVisible(fn(ActiveRow $row): bool => !$row->locked); return $grid; }
The grid never changes the Selection given to it - it works with clones.
Installation
composer require modul-is/datagrid
npm install @modul-is/datagrid @modul-is/form bootstrap@6.0.0-alpha.1 naja nette-forms
import naja from 'naja'; import { initForms } from '@modul-is/form'; import { initDatagrid } from '@modul-is/datagrid'; import '@modul-is/form/css'; import '@modul-is/datagrid/css'; initForms(naja); initDatagrid(naja); document.addEventListener('DOMContentLoaded', () => naja.initialize());
Optional DI extension with defaults of all grids:
extensions: modulisDatagrid: ModulIS\Datagrid\DI\DatagridExtension modulisDatagrid: align: center # default align of the columns (start, center, end) perPageList: [10, 25, 50] rememberState: false # state of the grids in the session texts: # texts of the grid, see Datagrid::$defaults noData: Nic nenalezeno
Icons are taken from modul-is/form (modulisForm: icons: fontawesome), the grid uses check, remove, eye and download.
Columns
| Method | Column |
|---|---|
addText($key, $label, ?$column) |
value as it is |
addNumber(...) |
setFormat($decimals, $decimalSeparator, $thousandsSeparator) |
addDateTime(...) |
setFormat('j. n. Y') - DateTime or a string |
addBool(...) |
check / cross icon, setIconTrue(), setIconFalse() |
addDial($key, $label, $list, ?$column) |
value translated by a list |
addLink($key, $label, $destination, ?$parameters, ?$column) |
value as a link, setNewTab(), setLinkClass() |
addStatus($key, $label, $options, ?$column) |
button with a menu of the options, setColors(), setConfirm(), onChange[] |
addTags($key, $label, fn(ActiveRow $row): iterable, ?$column) |
tags as badges - the callback returns key => text (usually a related table), setColors([key => 'danger'] | fn($key, $tag): ?string) (default secondary), setStyle('outline'|'subtle'|'solid'), setLimit(2) - one line with the others under a +N menu, without the limit all wrap; $column is for sorting and filtering only, the export has the texts separated by a comma |
addProgress(...) |
percent with a bar - setMax(100) (setMax(1) for a ratio), setColors([0 => 'danger', 30 => 'warning', 90 => 'success']) (lowest percent of the color, default primary), setFormat(); over the maximum a full bar with the real percent, the export has the percent as a number |
$column is the path of the value in the row - default the key, table.column for a referenced row (chained
a.b.column), :table.column for the first related row. The key itself can be the path, $column is then needed
only when the key differs - sorting and filtering of the column use the path too (addText('insurance.company.name', 'Skupina')->setSortable()->setFilterText()).
Own cell block of such a column is {define col-insurance.company.name}. Settings of all columns:
setSortable(true|string|Closure)- by the column, by another database column / expression, or by own sortingfn(Selection $selection, string $direction)setRenderer(fn(ActiveRow $row): string|Html|null),setTemplate($file, $parameters)(gets$row,$column),setReplacement($list)setAlign('start'|'center'|'end')- header, filter and cells of the column, defaultcenter(Datagrid::setDefaultAlign()),setWidth(15)(percent) orsetWidth('8rem'),setClass(),setAttributes()setTruncate()- cells on one line cut by an ellipsis, the whole text in the title; the column takes its width, or shares the space left by the other columns, but it is never narrower than its header.setWidth('8rem', fixed: true)keeps the width whatever the content is - the header and the cells are truncated. A status column is never truncated (its menu would be cut), an own cell (col-{key},setTemplate()) is truncated without the titlesetImage('country.flag_url' | fn(ActiveRow $row): ?string, Column::ImageSmall|ImageMedium|ImageLarge, round: false)- image in front of the content (flag, logo, avatar), path of the URL in the row or a callback, rows without the URL have none; not used by own cells, the export has the text onlysetEditable(fn($id, string $value) => ..., 'text'|'number'|'date'|'textarea'|'select', ?$items)- edited by a click,->setValue(fn($row)),->setCondition(fn($row): bool)setFilterText(),setFilterSelect(),setFilterMultiSelect(),setFilterDate(),setFilterDateRange(),setFilterRange()- filter in the header of the column
Filters
A filter with the key of a column is shown in the header of the column, other filters (addFilterText(),
addFilterSelect(), ... of the grid) above the table - setOuterFilters() shows all of them above the table.
$grid->setOuterFilters(); // all filters above the table $grid->setOuterFilterColumns(3); // filters in one row: 1, 2, 3, 4 (default), 6 or 12 $grid->setCollapsibleOuterFilters(); // hidden under the button "Filtr" - shown while a filter is active
| Filter | Condition |
|---|---|
| text | every word in one of the columns (LIKE %word%), setExact(), setSplitWords(false) |
| select | column = value, prompt "~ Vše ~" added (unless the items have the key ''), setPrompt(), setSearch() |
| multiselect | column IN (...) |
| date / date range | DATE(column) = / >= / <= |
| range | column >= / <=, decimal comma accepted |
setCondition(fn(Selection $selection, mixed $value): void) replaces the condition - the value is normalized (valid item of
a select, Y-m-d date, ['from' => ?, 'to' => ?] of ranges). setDefaultFilter(['active' => 1]) applies until the user
changes the filter.
Grid
$grid->setPrimaryKey('id'); // also 'car.id' $grid->setDefaultSort(['created' => 'DESC']); // column key or a database column $grid->setPerPageList([10, 20, 50], default: 20); $grid->setPagination(false); $grid->setRememberState(); $grid->setRowCallback(fn(ActiveRow $row, Html $tr) => $tr->class($row->active ? null : 'opacity-50')); $grid->setTemplateFile(__DIR__ . '/grid.latte'); // {extends $originalTemplate}, override blocks $grid->addToolbarButton(':Admin:User:add', 'Přidat')->setIcon('plus')->setColor('primary');
Actions
addAction($destination, ?$parameters, ?$caption) - destination with : is a presenter link, signal! belongs to the parent
of the grid, other destinations are actions of the current presenter. Parameters map link parameters to columns of the row
(default ['id' => primary key]). setIcon(), setTitle(), setColor(), setClass() accept a Closure(ActiveRow) too.
addCallbackAction($key)->onClick[] = fn($id) => ... is handled by the grid itself, the row is redrawn afterwards.
Group actions
$grid->addGroupAction('Smazat')->setColor('danger')->setConfirm('Smazat vybrané?') ->onSelect[] = fn(array $ids) => ...; $grid->addGroupAction('Přesunout', $categoryPairs) // menu of the options ->onSelect[] = fn(array $ids, int|string $categoryId) => ...; $grid->setGroupSelectable(fn(ActiveRow $row): bool => !$row->locked);
Exports
$grid->addExportCsv('CSV', 'users.csv', filtered: true, encoding: 'windows-1250'); $grid->addExport('XLSX', fn(Selection $selection, Datagrid $grid) => $this->sendXlsx($selection), filtered: true);
Every export is a button above the table. filtered: true exports the rows of the active filter, false (default) all rows
of the source - both in the active sorting and without pagination.
addExportCsv($caption, $fileName, $filtered, $encoding = 'UTF-8', $delimiter = ';', $bom = true)- columns of the grid (->setColumns([...keys])for own columns or order), cells as their text without HTML, numbers without the thousands separatoraddExport($caption, $callback, $filtered)- own export, the callback gets the rows (SelectionofActiveRow, iterable) and the grid, and sends a response ($grid->getPresenter()->sendResponse(...)) or terminates the presenter
Detail of a row
$grid->setDetail(__DIR__ . '/detail.latte', ['types' => $types]); // template gets $row $grid->setDetail(fn(ActiveRow $row) => Html::el('p')->setText($row->note)) ->setVisible(fn(ActiveRow $row): bool => $row->note !== null);
Settings of the columns
The button "Sloupce" above the table opens a dialog where the user changes the order of the columns (drag and drop or arrows)
and hides some of them. The button is shown only when setColumnSettings() is called. The grid does not store anything -
the application passes the settings loaded from its storage and stores the new ones in the callback (null = back to the defaults):
$grid->setColumnSettings( $this->GridSettingRepository->get($userId, 'contractGrid'), // array{order: list<string>, hidden: list<string>}|null fn(?array $settings) => $this->GridSettingRepository->save($userId, 'contractGrid', $settings) ); $grid->applyColumnSettings($settings); // order and hidden columns without the button
Unknown keys (columns removed since the settings were stored) are ignored, columns missing in the order (added later) are behind the ordered ones. A filter and sorting of a hidden column are not applied. Exports keep all columns.
Menu of a column
$grid->setColumnMenu() adds a button with a menu to the header of each column. A column gets only the items it supports:
- sorting ascending / descending - sortable columns (
sortBy($key, 'ASC'|'DESC')without the menu) - hiding the column and "Spravovat sloupce" (opens the dialog above) - only with
setColumnSettings(), the hidden column is stored by its callback (hideColumn($key)without the menu), the last visible column cannot be hidden
Texts of the items are columnMenu, sortAsc, sortDesc, hideColumn and manageColumns (setTexts()).
Redraw
$grid->reload() redraws the grid (AJAX) or reloads the page, $grid->redrawItem($id) redraws one row.
Client side
assets/js - filters submitted while typing (focus and typed text survive the redraw), confirmation dialog of actions
(data-datagrid-confirm), checkboxes of group actions, detail of a row, editable cells, collapsible outer filters and the dialog
of the settings of the columns. All listeners are on the
document, grids in redrawn snippets need no initialization.
The grid writes no style attributes (blocked by CSP without 'unsafe-inline') - widths of the columns and bars of
the progress are in data-datagrid-style and the client side sets them by CSSOM, after a redraw too.
Development
composer install
npm install
npm run demo # demo page in demo/www (SQLite database created in demo/temp)
vendor/bin/tester -C tests/
vendor/bin/phpstan analyse
php vendor/modul-is/coding-standard/ecs check src demo/app --preset php84