Download the PHP package kevinpirnie/kpt-datatables without Composer

On this page you can find all versions of the php package kevinpirnie/kpt-datatables. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package kpt-datatables

KPT DataTables

GitHub Issues Last Commit

PHP Discord Kevin Pirnie

Advanced PHP DataTables library with full CRUD operations, multi-table JOIN support, per-column filter accordion, calculated columns, footer aggregations, inline editing, Select2 AJAX dropdowns, file uploads, bulk actions, tabbed modal forms, and a theme system covering UIKit3, Bootstrap 5, Tailwind CSS, and a framework-agnostic Plain theme. All rendering is server-side PHP with client-side interactivity handled by a zero-dependency vanilla JS class.


Table of Contents


Requirements


Installation


Dependencies

Package Purpose
kevinpirnie/kpt-database PDO database wrapper with fluent query builder
kevinpirnie/kpt-logger Internal debug/error logging

Quick Start


Asset Inclusion

Assets must be included before the rendered table HTML. The static helper methods handle framework CDN links, theme-specific CSS, and all library JS in one call.

Parameter Type Description
$theme string 'uikit', 'bootstrap', 'tailwind', 'plain'
$includeCdn bool Include framework assets from CDN
$useMinified bool Use minified CSS/JS versions

UIKit example:

Bootstrap example:

Tailwind / Plain (no CDN):

Tailwind CSS must be compiled separately. See Building Assets.


AJAX Handling

All CRUD operations, search, pagination, sorting, filtering, and bulk actions are handled server-side through a single AJAX endpoint — the same URL that renders the page. The AJAX handler must be invoked before any HTML output.

The handleAjax() method internally routes the action parameter to the appropriate handler and outputs JSON before calling exit. Supported actions dispatched automatically by the JS layer:

Action Trigger
fetch_data Page load, sort, search, filter, pagination
fetch_record Edit button click (loads record into modal)
add_record Add form submit
edit_record Edit form submit
delete_record Delete confirmation
bulk_action Bulk action execute button
inline_edit Inline field save
upload_file Standalone file upload during inline image edit
fetch_aggregations After each data load when footer aggregations are configured
fetch_select2_options Select2 dropdown search
action_callback Custom row action with PHP callback

Themes

The theme is set via the fluent theme() method. It configures all CSS class mappings used throughout rendering and controls which CDN assets are included.

Theme Description
'uikit' UIKit 3 (default)
'bootstrap' Bootstrap 5
'tailwind' Tailwind CSS (requires compilation)
'plain' Framework-agnostic, kp-dt-* classes only

Core Configuration Methods

All methods return $this for fluent chaining unless otherwise noted.

table()

Sets the primary database table. Supports table aliases. Auto-loads the table schema from the database for field type detection and form generation.

When an alias is used, the base table name (without alias) is automatically tracked separately for INSERT, UPDATE, and DELETE operations.


primaryKey()

Overrides the auto-detected primary key. Supports qualified (aliased) names.

The library automatically strips the table prefix when building WHERE id = ? clauses for mutations.


database()

Configures or replaces the database connection after construction.


columns()

Defines which columns to display. Keys are database column names (supports dot notation for joined tables and expression AS alias syntax). Values are display labels or full configuration arrays.

Simple format:

Enhanced format (type overrides, options, form classes):

See Column Definition Reference for all supported type overrides.


join()

Adds a SQL JOIN clause. Multiple joins are supported and applied to all data, count, and aggregation queries.

Parameter Description
$type 'LEFT', 'RIGHT', 'INNER', 'FULL OUTER'
$table Table name, optionally with alias (e.g., 'users u')
$condition Raw ON condition (e.g., 'o.user_id = u.id')

where()

Adds static server-side WHERE conditions that always apply to data queries, count queries, and mutations. These are invisible to the user.

Each condition requires field, comparison, and value keys.

Supported comparison operators: =, !=, <>, >, <, >=, <=, LIKE, NOT LIKE, IN, NOT IN, REGEXP

For IN / NOT IN pass an array as the value:

WHERE conditions applied through where() are also appended to UPDATE and DELETE queries for security, ensuring mutations cannot affect records outside the configured scope.


filter()

Configures the user-facing collapsible filter accordion rendered above the table. Each key is a database column (dot notation supported). Values can be a shorthand operator string or a full configuration array.

Shorthand:

Full configuration:

See Filter Accordion Reference for all supported operators and input types.


sortable()

Defines which columns produce clickable sort headers. Pass column names exactly as they appear in columns() keys, or use alias names for aliased expressions.

Clicking a sortable header cycles ASC → DESC → ASC. Sort icons update accordingly.


inlineEditable()

Marks specific columns as double-click-to-edit. The appropriate inline editor (text input, select, boolean toggle, image uploader, etc.) is determined from the column's type in the schema or columns() override.

Supported inline edit types: text, email, number, date, datetime-local, textarea, select, select2, boolean, image, datepicker.


perPage()

Sets the initial (default) number of records displayed per page.


pageSizeOptions()

Configures the options available in the per-page selector. When $includeAll is true, an "All records" option (value 0) is appended.

The per-page selector renders as a <select> dropdown by default, or as a button group when renderPageSizeSelectorComponent(true) is called.


search()

Enables or disables the global search input. Enabled by default.


defaultSort()

Sets the column and direction used for initial data load. Without this, data loads in database natural order.


groupBy()

Adds a GROUP BY clause to data and count queries. When a group-by is active, the count query wraps the grouped result in a subquery to return the true number of groups. Aggregation queries also wrap accordingly.


Action Configuration

actions()

Configures the built-in action column (edit / delete buttons) with placement and visibility.


actionGroups()

Replaces the default edit/delete buttons with a flexible group system that supports built-in actions, custom link actions, PHP callback actions, and raw HTML injection — all with configurable ordering and separators.

Each element of $groups is either:

Built-in actions:

Custom link action:

Placeholder substitution{id} and {column_name} placeholders in href, title, onclick, and attributes values are replaced with the row's actual data:

PHP callback action (server-side execution):

HTML injection — inject arbitrary HTML before or after any action or group:


Bulk Actions

Enables a checkbox column and a toolbar for performing operations on multiple selected records simultaneously.

With default delete-only:

With custom actions:

The callback signature is function(array $ids, Database $db, string $baseTableName): bool|int.

Clicking a row (outside the action/check cell) toggles its checkbox. A "select all" checkbox in the header selects the entire current page.


Modal Forms

addForm()

Configures the "Add Record" modal and its form fields.


editForm()

Configures the "Edit Record" modal. The primary key field is automatically injected as a hidden input and populated by the JS fetch_record AJAX call.


Field Types

All field configurations share common keys:

Key Type Description
type string Field type (see table below)
label string Display label
required bool Add required attribute and asterisk
placeholder string Placeholder text
value mixed Default value
default mixed Alias for value
disabled bool Disable the field
class string Extra CSS class on the wrapper
attributes array Additional HTML attributes
options array value => label pairs for select/radio

Supported types:

Type Renders As Notes
text <input type="text"> Default fallback
email <input type="email">
number <input type="number">
url <input type="url">
tel <input type="tel">
password <input type="password">
hidden <input type="hidden"> No label or wrapper rendered
textarea <textarea>
boolean <select> with Active/Inactive Stores 1 / 0
checkbox <input type="checkbox"> Value 1 when checked
radio Radio button group Requires options
select <select> dropdown Requires options
select2 AJAX searchable dropdown Requires query
file <input type="file">
image URL input + file upload + preview
datepicker Styled date picker with format support
static Read-only <p> element Not submitted; renders content key or DB value

select2 field extra keys:

Key Type Default Description
query string SQL query returning ID and Label columns
placeholder string 'Select...' Dropdown placeholder
min_search_chars int 0 Minimum characters before search fires
max_results int 50 Maximum results returned

Query parameter substitution — use {field_name} placeholders in select2 queries to filter options based on other fields in the same record:

datepicker field extra keys:

Key Type Default Description
formatter string 'YYYY-MM-DD' Display format using YYYY, MM, DD tokens

Values are stored internally as YYYY-MM-DD regardless of display format.

static field extra keys:

Key Type Description
content string Hardcoded text to display; omit to auto-populate from the DB record

Tabbed Forms

Any form field can be assigned to a named tab by adding a tab key. Fields without a tab key are grouped under a "General" tab that is prepended automatically.

Tab navigation is rendered using the active theme's tab component (UIKit uk-tab, Bootstrap nav-tabs, or the custom kp-dt-tabs plain/tailwind component).


allow_on Field Overrides

Fields in the edit form can be conditionally modified when a specific condition on the fetched record is met. The server evaluates the condition during fetch_record and sends field overrides back to the client.

Supported operators for allow_on: ==, !=, >, >=, <, <=, IN, NOT IN

To remove an attribute set null or false as its value in set_attributes.


Calculated Columns

Computed columns are added to the SELECT as SQL expressions and rendered in the table like any other column. They cannot be edited inline.

calculatedColumn()

Builds the expression from an array of column names joined by an operator.

Operator
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus

calculatedColumnRaw()

Accepts a raw SQL expression for complex calculations.


Footer Aggregations

Calculates SUM and/or AVG per column and displays the results in the table footer. Two scopes are supported: page (calculated client-side from the current page data) and all (calculated server-side across the full filtered recordset).

footerAggregate()

Parameter Options
$type 'sum', 'avg', 'both'
$scope 'page', 'all', 'both'

footerAggregateColumns()

Applies the same type and scope to multiple columns at once.

Aggregation columns work with calculated columns — pass the alias name:


Styling

tableClass()

Overrides the default CSS classes on the <table> element.


rowClass()

Sets a base CSS class applied to every <tr>. The record's primary key value is appended, e.g., my-row-42.


columnClasses()

Applies CSS classes to specific <td> (and <th>) elements by column key.


File Uploads

Configures server-side validation for file uploads submitted through file or image form fields, or via inline image editing.

Parameter Default Description
$uploadPath 'uploads/' Destination directory (created if absent)
$allowedExtensions ['jpg','jpeg','png','gif','pdf','doc','docx'] Whitelist of extensions (without dot)
$maxFileSize 10485760 (10 MB) Maximum size in bytes

Uploaded files are stored with a uniqid() prefix to prevent collisions. The stored filename (not path) is saved to the database field.


Rendering

renderDataTableComponent()

Renders the complete DataTable HTML: the container, filter accordion, table (with header, body, footer, aggregation rows), all modals, and the JS initialization script. This is the primary output method.


Static Methods

getCssIncludes()

getJsIncludes()


Standalone Component Renderers

Individual components can be rendered outside renderDataTableComponent() for custom layouts.

When calling renderFilterAccordionComponent() manually, remove the internal call by ensuring the filter accordion is not rendered inside renderContainer(). Rendering it twice causes duplicate DOM IDs.


Filter Accordion Reference

Operators

Operator SQL Behavior Input Rendered
= Exact match Text input
!= Not equal Text input
>, >=, <, <= Numeric/date comparison Text or number input
LIKE Partial match (%value% auto-wrapped) Text input
NOT LIKE Inverse partial match Text input
IN Comma-separated value list Text input (hint shown)
NOT IN Exclude comma-separated list Text input
BETWEEN Date or number range Two side-by-side inputs with From/To labels
REGEXP Regular expression match Text input

Input Types

Type Renders
text (default) <input type="text">
number <input type="number">
date <input type="date">
datetime-local <input type="datetime-local">
email <input type="email">
boolean <select> with All / Active / Inactive
select <select> — requires options in config

Active Filter Badge

When filters are applied, a count badge appears in the accordion header. The badge updates automatically as filters are added or removed and clears when resetFilters() is called.


WHERE Conditions Reference

where() conditions differ from filter() conditions:

where() filter()
Who sets it Developer End user (via accordion UI)
Persists across requests Always Only while inputs are filled
Applied to mutations Yes (UPDATE, DELETE) No
Visible to user No Yes

Both are applied simultaneously — where() conditions are evaluated first, filter conditions are appended with AND.


Column Definition Reference

When using the enhanced column format (array value instead of string label), the following keys control display and form behavior:

Key Description
label Display label in table header and form
type Override the auto-detected field type for display and inline editing
options value => label map for select type display and inline editing
query SQL query for select2 type (must return ID and Label columns)
min_search_chars Minimum characters before select2 search fires
max_results Maximum select2 results
formatter Date format string for datepicker type
class Extra CSS class on the column's form wrapper
attributes Extra HTML attributes on the column's form input
placeholder Placeholder text

Auto-detected types from MySQL schema:

MySQL Column Type Detected As
tinyint(1), boolean, bit(1) boolean
int, bigint, smallint, etc. number
decimal, float, double number
datetime, timestamp datetime-local
date date
time time
text, longtext, mediumtext textarea
enum select
varchar text (or email if column name contains "email")

JavaScript API

The DataTablesJS class is instantiated automatically by the PHP renderInitScript() output and exposed on window.DataTables. You can call its methods directly from inline event handlers or your own JS.

Core Methods

Method Description
DataTables.loadData() Reload table data with current search/sort/filter/page state
DataTables.goToPage(page) Navigate to a specific page number
DataTables.resetSearch() Clear search input and reload
DataTables.applyFilters() Read filter inputs and reload
DataTables.resetFilters() Clear all filter inputs and reload
DataTables.changePageSize(size, event) Change records per page

CRUD Methods

Method Description
DataTables.showAddModal(event) Open the add record modal
DataTables.showEditModal(id) Fetch record and open edit modal
DataTables.showDeleteModal(id) Open delete confirmation modal
DataTables.confirmDelete() Execute the pending delete
DataTables.submitAddForm(event) Submit the add form via AJAX
DataTables.submitEditForm(event) Submit the edit form via AJAX

Selection and Bulk

Method Description
DataTables.toggleSelectAll(checkbox) Toggle all row checkboxes
DataTables.toggleRowSelection(checkbox) Toggle a single row checkbox
DataTables.executeBulkAction() Execute action from <select> bulk action UI
DataTables.executeBulkActionDirect(action, event) Execute a named bulk action from a button

Notifications and Modals

Method Description
DataTables.showNotification(message, status) Show themed notification ('success', 'danger', 'warning')
DataTables.showModal(modalId) Open a modal by ID
DataTables.hideModal(modalId) Close a modal by ID
DataTables.showConfirm(message) Show themed confirm dialog, returns Promise

Global Helper Objects

Object Purpose
KPDataTablesPlain Modal and notification helpers for plain/tailwind themes
KPDataTablesBootstrap Bootstrap Toast and modal confirm helper
KPDataTablesDatepicker Date formatting and ISO parsing utilities
KPTSelect2 AJAX-powered Select2 class (no jQuery)

Building Assets

Node.js tooling is used to compile and minify JS and CSS. Install dependencies first:

Available npm Scripts

Command Description
npm run build Compile Tailwind CSS, then minify all JS and CSS
npm run build:js Minify JS bundle only
npm run build:css Minify all theme CSS files only
npm run build:tailwind Compile Tailwind CSS from tailwind.src.css
npm run watch:tailwind Watch and recompile Tailwind CSS on changes
npm run dev:tailwind One-shot Tailwind compile without minification
npm run dev Tailwind compile + minify all

Output Locations

Asset Output
JS bundle src/assets/js/dist/kpt-datatables.min.js
CSS (per theme) src/assets/css/dist/{theme}.min.css
Tailwind source src/assets/css/themes/tailwind.css

Testing

Tests cover UIKit, Bootstrap, Tailwind, and Plain theme rendering as well as AJAX handler routing. The CI matrix runs against PHP 8.2, 8.3, and 8.4 with both lowest and highest dependency sets.


Security

For security-related issues, email [email protected] rather than opening a GitHub issue.


Full Configuration Example


Browser Support

Chrome 60+, Firefox 60+, Safari 12+, Edge 79+


Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/my-feature)
  3. Commit your changes (git commit -m 'Add my feature')
  4. Push to the branch (git push origin feature/my-feature)
  5. Open a Pull Request

Roadmap


License

The MIT License (MIT). See LICENSE for details.


Support


Made with ❤️ by Kevin Pirnie


All versions of kpt-datatables with dependencies

PHP Build Version
Package Version
Requires php Version >=8.2
kevinpirnie/kpt-database Version ^1.0
kevinpirnie/kpt-logger Version ^1.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package kevinpirnie/kpt-datatables contains the following files

Loading the files please wait ...