PHPackages                             siensis/kpacrud - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Admin Panels](/categories/admin)
4. /
5. siensis/kpacrud

ActiveLibrary[Admin Panels](/categories/admin)

siensis/kpacrud
===============

KpaCrud Library permits to generate automatically CRUD pages from a DB table

02171PHP

Since May 15Pushed 11mo ago1 watchersCompare

[ Source](https://github.com/SIENSIS/KpaCrud)[ Packagist](https://packagist.org/packages/siensis/kpacrud)[ RSS](/packages/siensis-kpacrud/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

- [KpaCrud Library](#kpacrud-library)
- [Install](#install)
    - [Install with composer](#install-with-composer)
    - [Install manually](#install-manually)
- [Publish command](#publish-command)
- [Constructor](#constructor)
- [Routes file](#routes-file)
- [Config file parameters](#config-file-parameters)
- [Method setConfig](#method-setconfig)
- [Method setTable](#method-settable)
- [Method setPrimaryKey](#method-setprimarykey)
- [Method setColumns](#method-setcolumns)
- [Method setRelation](#method-setrelation)
- [Method addWhere](#method-addwhere)
- [Method limit](#method-limit)
- [Method setColumnsInfo](#method-setcolumnsinfo)
    - [Available parameters](#available-parameters)
    - [Set field name](#set-field-name)
    - [Field types and samples](#field-types-and-samples)
        - [Number field type](#number-field-type)
        - [Range field](#range-field)
        - [Make a field **required**](#make-a-field-required)
        - [Make a field **Invisible**](#make-a-field-invisible)
        - [Checkbox field](#checkbox-field)
        - [Date field with default value in Add page](#date-field-with-default-value-in-add-page)
        - [Datetime field with default value in Add page](#datetime-field-with-default-value-in-add-page)
        - [Password field type](#password-field-type)
        - [Dropdown field type](#dropdown-field-type)
- [Method hideHeadLink](#method-hideheadlink)
- [Method addPostAddCallBack and addPostEditCallBack](#method-addpostaddcallback-and-addposteditcallback)
- [Functions isViewMode, isExportMode, isAddMode, isEditMode, isDelMode, isTrashMode](#functions-isviewmode-isexportmode-isaddmode-iseditmode-isdelmode-istrashmode)
- [Method addItemFunction](#method-additemfunction)
- [Method addItemLink](#method-additemlink)
- [Library Exceptions](#library-exceptions)

KpaCrud Library
===============

[](#kpacrud-library)

- [Samples and how to's](samples.md)
- [Change list](changes.md)
- [TODO](todo.md)

Install
=======

[](#install)

Install with composer
---------------------

[](#install-with-composer)

**Option 1:**

You need to add `SIENSIS/KpaCrud` require with composer tool.

```
> composer require siensis/kpacrud:dev-master

```

**Option 2:**

or modify `composer.json` and add the package to require items into `composer.json`

```
    "require": {
        "siensis/kpacrud": "dev-master"
    },
```

**Finally**

Execute `composer update` command to update your project settings

```
> composer update

```

> 💡 **Idea**
>
> If you have any problem, probably you need to update you composer, executing:
>
> composer self-update --2

Install manually
----------------

[](#install-manually)

Download KpaCrud project and extract into your project in a ThirdPary folder, with this structure:

> 📁 app
>
> 📁 public
>
> 📁 tests
>
> 📁 vendor
>
> 📁 ThirdParty
>
> |---- 📁 SIENSIS
>
> |---- |---:file\_folder: KpaCrud

Then you need modify autoload config file `app/Config/Autoload.php` and add your new PSR4 package path.

```
public $psr4 = [
    APP_NAMESPACE => APPPATH, // For custom app namespace
    'Config'      => APPPATH . 'Config',
    'SIENSIS\KpaCrud' => ROOTPATH . 'ThirdParty'.DIRECTORY_SEPARATOR.'SIENSIS'.DIRECTORY_SEPARATOR.'KpaCrud'.DIRECTORY_SEPARATOR.'src'
];
```

> 💡 **Idea**
>
> Constant **`DIRECTORY_SEPARATOR`** is used to prevent path problems in Linux or Windows servers

Publish command
===============

[](#publish-command)

`KpaCrud` has their command `kpacrud:publish` to generate automatically a sample controller, a view sample, a custom config file and the KpaCrud lang files into your App folder.

To generate this files, you need to execute this command:

```
> php spark kpacrud:publish
Publish demo Controller? [y, n]:
Publish Views? [y, n]:
Publish Config file? [y, n]:
Publish Language file? [y, n]:

```

If files already exists, publish command ask you for confirmation. Otherwise if you sure to overwrite files, you can call `kpacrud:publish` with `-f` option, like:

```
> php spark kpacrud:publish -f

```

Constructor
===========

[](#constructor)

You can save all config parameters into `KpaCrud.php` file in `App\Config` folder.

```
$crud = new KpaCrud(); //loads default configuration
```

Loads default parameters with `configDefaultName` as the config collection parameters. If you would like to load another collection, you can indicate it in constructor.

With this sample you KpaCrud library loads `listView` defined parameters.

```
$crud = new KpaCrud('listView'); //loads listView configuration
```

Routes file
===========

[](#routes-file)

KpaCrud library works with GET and POST methods, you need to create a GET and POST route to your controller function.

```
$routes->match(['get','post'],'/route/to/crud', 'SampleKpaCrudController::demo_function');
```

POST Method is used by KpaCrud in `Add submit`, `Delete confirm` and `Edit submit`.

Config file parameters
======================

[](#config-file-parameters)

In the file `App\Config\KpaCrud.php` you can can store parameters collections identified with a name and the collection parameter used as default.

Param nameTypeDefaultDescriptioneditablebooleantrueDefines if row has edit buttonremovablebooleantrueDefines if row has delete button**Table tools**langstringDefines the URL of JS file language for Datatables JQuery toolsortablebooleantrueDefines if table has enabled the sortable featurefilterablebooleantrueDefines if table has enabled the searching toolpagingbooleantrueDefines if table has enabled the paging toolsnumeratebooleantrueDefines library numerate rows**Table features**pagingTypestringDetermines the paging type, values are: `numbers`, `simple`, `simple_numbers`, `full`, `full_numbers`, `first_last_numbers`defaultPageSizeintDetermines the page size set as defaultrememberStatebooleanfalseDefines if table remembers last order column, search, etc**Right toolbar**add\_buttonbooleantrueEnables add button in top right toolbarshow\_buttonbooleantrueEnables show button in list itemsrecycled\_buttonbooleantrueEnables trash buttons in top right toolbar (Empty trash, show trash)exportXLSbooleantrueEnables export XLS button in top right toolbarprintbooleantrueEnables print button in top right toolbar**Left toolbar**multideletebooleantrueEnables the multi select feature in table list to remove item or to move to trash if softDelete is enableddeletepermanentbooleantrueEnables the multi select feature in table list to remove item permanently if softDelete is enabled**Model features**useSoftDeletesbooleantrueEnables the soft delete feature, then items are mark as delete and they can use trash viewshowTimestampsbooleanfalseEnables to show fields created\_at and updated\_at in view pagecreatedFieldstring'created\_at'Name of created\_at field into databaseupdatedFieldstring'updated\_at'Name of update\_at field into databasedeletedFieldstring'deleted\_at'Name of deleted\_at field into databaseIn config file you can define the default collection with `configDefaultName`.

The KpaCrud config file provided, are defined `onlyView`, `listView` and `default` (acts as fullView ).

Method setConfig
================

[](#method-setconfig)

You can set config parameters after object Library is created. The function setConfig can change all config parameters if you set a collection name as a parameter.

```
$crud->setConfig('onlyView');
```

even, you can change only a [parameter](#config-file-parameters), like:

```
$crud->setConfig(['editable'=>false]);                     // Sets editable configuration to false
$crud->setConfig(['editable'=>false,'removable'=>false]);  //Sets editable and removable config parameter to false
```

See also [How to create your custom App\\KpaCrud config file](samples.md#how-to-create-your-custom-appkpacrud-config-file)

Method setTable
===============

[](#method-settable)

This method sets table name to generate CRUD pages, when you set table name, method can detect primary key. By default, `setTable` doesn't detect primary key. To load automatically primary key, you need to set `true` the `loadPrimaryKeys` function flag, like this sample:

```
$crud->setTable('news', true);    // Primary key autoload feature
```

otherwise, you can only specify table name.

```
$crud->setTable('news');
```

Method setPrimaryKey
====================

[](#method-setprimarykey)

This method adds primary key to CRUD Library, you can use it if you doesn't use automatic primary key load. You can call function for every key, if your table has more than a primary key.

```
$crud = new KpaCrud();

$crud->setTable('tokens');
$crud->setPrimaryKey('tokenid');
$crud->setPrimaryKey('subject');
```

> [⚠️ Exception](#library-exceptions)
>
> If the primary key string field doesn't exists, method will throw an exception

Method setColumns
=================

[](#method-setcolumns)

This method will permit to set columns that will be shown in CRUD Page view or CRUD Trash view if enabled.

```
$crud = new KpaCrud('listView');        // loads listView configuration
$crud->setTable('news');                // load news table
$crud->setPrimaryKey('id');             // set primary key to id field
$crud->setColumns(['id', 'title', 'data_pub']); // set fields to show in listView
```

> [⚠️ Exception](#library-exceptions)
>
> Function throws this
>
> - Table is null or not defined
> - Table doesn't exists in database
> - Field doesn't exists in table

Method setRelation
==================

[](#method-setrelation)

With this method you can set a relation 1=&gt;N from a table to another one, for CRUD operations.

```
  $crud = new KpaCrud('listView');                          // loads listView configuration

  $crud->setTable('auth_groups_users');                     // set table name

  $crud->setPrimaryKey('group_id');                         // set primary key
  $crud->setPrimaryKey('user_id');                          // set primary key

 // function setRelation($fieldName, $relatedTable, $relatedField, $display_as = null)

 // display_as is the column name to show in edit / view mode
 // if not set, relatedfield is shown
  $crud->setRelation('group_id', 'auth_groups', 'id', 'name');
  $crud->setRelation('user_id', 'users', 'id', 'username');
```

The display\_as parameter is to indicated the field name from related table, to show instead relatedField. If parameter is null, will show first upper case related field name

They can display more than a relation, like example.

Method addWhere
===============

[](#method-addwhere)

This method permits to filter data show in the KpaCrud admin table. You can set filter as an associative array, or you can set SQL where expression as string.

The third parameter permits you to use OR conjuntion in a where clause

```
    $crud->addWhere ("id","3");
    $curd->addWhere ("id","4", true);
```

This clause generates

```
WHERE id=3 OR id=4
```

> ⚠️ **WARNING!!**
>
> If you use parameters with this function, you need to check it to avoid SQL injection

Method limit
============

[](#method-limit)

This method adds limit clause to database query, usefull to show limited data. Sintax as codeigniter querybuilder limit function

```
  $crud->limit(10);   // Produces: LIMIT 10

  $crud->limit(10, 20);  // Produces: LIMIT 20, 10
```

Method orderBy
==============

[](#method-orderby)

This method Adds order by clause to database query, usefull to show ordered data. Sintax as codeigniter querybuilder limit function

```
  $crud->orderBy('title', 'DESC');  // Produces: ORDER BY `title` DESC

  $crud->orderBy('title DESC, name ASC');  // Produces: ORDER BY `title` DESC, `name` ASC

  $crud->orderBy('title', 'DESC');  $builder->orderBy('name', 'ASC');   // Produces: ORDER BY `title` DESC, `name` ASC

  $crud->orderBy('title', 'RANDOM');  // Produces: ORDER BY RAND()

  $crud->orderBy(42, 'RANDOM');  // Produces: ORDER BY RAND(42)
```

Method setColumnsInfo
=====================

[](#method-setcolumnsinfo)

Available parameters
--------------------

[](#available-parameters)

The function setColumnsInfo permits to customize every database field.

ParameterTypeDescriptionname`string`Field name to show user in pagestype`string`Availables field types are: DEFAULT\_FIELD\_TYPE, READONLY\_FIELD\_TYPE, INVISIBLE\_FIELD\_TYPE, EMAIL\_FIELD\_TYPE, CHECKBOX\_FIELD\_TYPE,NUMBER\_FIELD\_TYPE, RANGE\_FIELD\_TYPE, DATE\_FIELD\_TYPE, DATETIME\_FIELD\_TYPE, TEXTAREA\_FIELD\_TYPE [(Check field types)](#field-types-and-samples)default`string`Field default value in add pagecheck\_value`string,bool,integer`Value stored when a checkbox is checked. **DEFAULT=1**uncheck\_value`string,bool,integer`Value stored when a checkbox is unchecked. **DEFAULT=0**html\_atts`array[string]`Others html attributes to add to field, like: required, placeholder, pattern, title, min, max, step...options`array`Options to show in a dropdown fieldexcludes`array`Values that are excluded to show into fieldnullable`string`Set to make a field nullable into DB. Their values serves to check into UISet field name
--------------

[](#set-field-name)

You can set the field name with the properties associative array like this sample:

```
'dbfieldname' => [
    'name' => 'Field name to show',
],
```

or you can set it directly, but in this last version, you can only set the name for a db field.

```
'dbfieldname' => 'Field name to show',
```

Field types and samples
-----------------------

[](#field-types-and-samples)

### Number field type

[](#number-field-type)

```
'dbfieldname' => [
    'name' => 'Demo number field',
    'type' => KpaCrud::NUMBER_FIELD_TYPE,
    'default' => '25',
    'html_atts' => [
        'min="1"',
        'max="50"',
    ]
],
```

### Range field

[](#range-field)

```
'dbfieldname' => [
    'name' => 'Demo text field',
    'type' => KpaCrud::RANGE_FIELD_TYPE,
    'default' => '25',
    'html_atts' => [        // html_atts are optional, but useful to costumize page
        'min="1"',
        'max="50"',
        'step="5"',
    ]
],
```

### Make a field **required**

[](#make-a-field-required)

```
'dbfieldname' => [
    'name' => 'Demo text field',
    'html_atts' => [
        "required",
        "placeholder=\"Add your info here\""
    ],
],
```

### Make a field **Invisible**

[](#make-a-field-invisible)

This field will be invisible in all views

```
'dbfieldname' => [
    'type' => KpaCrud::INVISIBLE_FIELD_TYPE
],
```

### Make a field **READ ONLY**

[](#make-a-field-read-only)

This field will be read only in add or edit view

```
'dbfieldname' => [
    'type' => KpaCrud::READONLY_FIELD_TYPE
],
```

### Checkbox field

[](#checkbox-field)

```
'dbfieldname' => [
    'name' => 'Demo text field',
    'type' => KpaCrud::CHECKBOX_FIELD_TYPE,
    'check_value' => '1',   // By default check_value=1. You can omit it is equal
    'uncheck_value' => '0'  // By default uncheck_value=0
],
```

### Date field with default value in Add page

[](#date-field-with-default-value-in-add-page)

```
'dbfieldtype' => [
    'type' => KpaCrud::DATE_FIELD_TYPE,
    'default' => '1-2-2022'  // you can set default date for add page
],
```

### Datetime field with default value in Add page

[](#datetime-field-with-default-value-in-add-page)

```
'dbfieldtype' => [
    'type' => KpaCrud::DATETIME_FIELD_TYPE,
    'default' => '1-2-2022 15:43'  // you can set default date for add page
],
```

### Password field type

[](#password-field-type)

This type permits to hide content data in edit page or new page. All fields typed as password are always hidden in view or delete views.

Password field type in the edit page adds a hidden form field to check programatically if user has changed the value. This feature permits you to combine with edit and new callback to store passwords hashed in you DB.

See [Samples file](samples.md)

### Dropdown field type

[](#dropdown-field-type)

You can create a custom dropdown item, to control values introduced in a field by user. You can define dropdown values with an associative array.

To make an identic checkbox with a dropdown, you can set item-value only, like this.

```
'active' => [
    'type' => KpaCrud::DROPDOWN_FIELD_TYPE,
    'options' => ["Disabled", "Active"],
    'html_atts'=>[
        "required",
    ]
],
```

```
'active' => [
    'type' => KpaCrud::DROPDOWN_FIELD_TYPE,
    'options' => ["0"=>"Disabled", "1"=>"Active"],
    'html_atts'=>[
        "required",
    ]
],
```

This samples generates

```

    Disabled
    Active

```

If you need to show a select value item in a dropdown, you can do it easily adding a null index item. Like this sample.

```
'active' => [
    'type' => KpaCrud::DROPDOWN_FIELD_TYPE,
    'options' => [""=>"Select option","Disabled","Active"],
    'html_atts'=>[
        "required",
    ]
],
```

This samples generates

```

    Select option
    Disabled
    Active

```

Method hideHeadLink
===================

[](#method-hideheadlink)

If you need to hide CSS/JS from head, you can use `hideHeadLink` function. Every link has its own id, the availables ones are:

IDDescriptionjs-queryJQuery Javascript CDNjs-bootstrapBootstrap JS filejs-datatablesDatatables plugin JS filejs-datatables-bootDatatables JS file for bootstrap themecss-bootstrapBootstrap CSS filecss-datatables-bootDatatables CSS for bootstrap themecss-fontawesomeFontawesome CSS fileSee ["How to change bootstrap, jquery or CSS/JS head links"](samples.md#how-to-change-bootstrap-jquery-or-cssjs-head-links) for a sample.

Method addPostAddCallBack and addPostEditCallBack
=================================================

[](#method-addpostaddcallback-and-addposteditcallback)

If you need to get post data to change anythig before `KpaCrud` uses this info to store it in database, you need to set an add or edit callback.

The function will receive post data and they must return post data modified or **`null`** if you need to cancel event, in this case `KpaCrud` showns a cancel message like: **` Error callback function cancel operation`**

Post data fields will use the name according this structure:

> data\_ + DATABASE\_FIELD\_NAME

See ["How to set a callback to store hashed password"](samples.md#how-to-set-a-callback-to-store-hashed-password) for a sample.

Functions isViewMode, isExportMode, isAddMode, isEditMode, isDelMode, isTrashMode
=================================================================================

[](#functions-isviewmode-isexportmode-isaddmode-iseditmode-isdelmode-istrashmode)

The functions functions `isViewMode`, `isExportMode`, `isAddMode`, `isEditMode`, `isDelMode`, `isTrashMode` permits you to know KpaCrud mode, to customize KpaCrud aspect.

**Sample**: You need to export all database fields but in list mode you would like to show only id and description fields.

See ["How to custom parameters according KpaCrud view mode"](samples.md#how-to-custom-parameters-according-kpacrud-view-mode) for a sample.

Method addItemFunction
======================

[](#method-additemfunction)

This function permits to declare a new icon function in every register. The function used as callback may be defined in your controllers.

The callback function used may returns a view as string. KpaCrud library uses this html information to show them in KpaCrud interface.

If you need a function to be called afterly, as post page or other like this, you can define invisible functions.

See [How to add a function for every register](samples.md#how-to-add-a-function-for-every-register) for a sample.

Method addItemLink
==================

[](#method-additemlink)

This function permits to declare a new icon link for every register. The function used as callback may be defined in your controllers.

```
        $crud->addItemLink('view', 'fa-file-o', base_url('route/to/link'), 'Tooltip for icon button');
        // GENERATES ICON

        $crud->addItemLink('show', 'fa-file-o', [base_url('route/to/link'),'hash'], 'Tooltip for icon button'));
        // GENERATES ICON

        $crud->addItemLink('show', 'fa-file-o', [base_url('route/to/link?param='),'hashquery'], 'Tooltip for icon button'));
        // GENERATES ICON

        $crud->addItemLink('show', 'fa-file-o', [base_url('route/to/link?param='),'queryid'], 'Tooltip for icon button'));
        // GENERATES ICON
```

Library Exceptions
==================

[](#library-exceptions)

Exception IDException1, 4, 8Table name is null2, 5, 9Table not exists in DB3, 6Field name not existsYou try to set a field name as ID or show as a column in list view, and this field doesn't exists7Field type unknownCheck available field types in documentation10ID Field name set to null

###  Health Score

18

—

LowBetter than 8% of packages

Maintenance37

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity14

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/ed27f0f560eb983a796e321c4a123c42674e52411154cbc2b7d5e28954b7ebeb?d=identicon)[devsiensis](/maintainers/devsiensis)

---

Top Contributors

[![SIENSIS](https://avatars.githubusercontent.com/u/104563618?v=4)](https://github.com/SIENSIS "SIENSIS (129 commits)")

---

Tags

codeigniter-librarycodeigniter4cruddatabase-management

### Embed Badge

![Health badge](/badges/siensis-kpacrud/health.svg)

```
[![Health](https://phpackages.com/badges/siensis-kpacrud/health.svg)](https://phpackages.com/packages/siensis-kpacrud)
```

###  Alternatives

[jeroennoten/laravel-adminlte

Easy AdminLTE integration with Laravel

4.0k4.8M43](/packages/jeroennoten-laravel-adminlte)[dmstr/yii2-adminlte-asset

AdminLTE backend theme asset bundle for Yii 2.0 Framework

1.1k1.8M67](/packages/dmstr-yii2-adminlte-asset)[dwij/laraadmin

LaraAdmin is a Open source Laravel Admin Panel / CMS which can be used as Admin Backend, Data Management Tool or CRM boilerplate for Laravel with features like CRUD Generation, Module Manager, Media, Menus, Backups and much more

1.6k68.7k](/packages/dwij-laraadmin)[filament/spatie-laravel-media-library-plugin

Filament support for `spatie/laravel-medialibrary`.

1764.8M125](/packages/filament-spatie-laravel-media-library-plugin)[bezhansalleh/filament-exceptions

A Simple &amp; Beautiful Pluggable Exception Viewer for FilamentPHP's Admin Panel

193195.9k13](/packages/bezhansalleh-filament-exceptions)[filament/infolists

Easily add beautiful read-only infolists to any Livewire component.

1220.8M36](/packages/filament-infolists)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
