PHPackages                             rashedalkhatib/yii2-datatables - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. rashedalkhatib/yii2-datatables

ActiveYii2-extension[Utility &amp; Helpers](/categories/utility)

rashedalkhatib/yii2-datatables
==============================

DataTables widget for Yii2

1.0.0(2y ago)1202MITCSS

Since Apr 21Pushed 2y ago1 watchersCompare

[ Source](https://github.com/RashedAlkhatib/yii2-datatables)[ Packagist](https://packagist.org/packages/rashedalkhatib/yii2-datatables)[ RSS](/packages/rashedalkhatib-yii2-datatables/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (5)Versions (2)Used By (0)

DataTable Widget
================

[](#datatable-widget)

Overview
--------

[](#overview)

The DataTable widget is used to create interactive and dynamic data tables. The provided JavaScript code demonstrates how to initialize DataTable with server-side processing, custom data handling, and column rendering and with full serverside Export .

installation
------------

[](#installation)

### in your Yii2 application :

[](#in-your-yii2-application-)

- Run : `composer require rashedalkhatib/yii2-datatables:1.0.0`
- go to your `../frontend/assets/AppAsset.php`
    - add `rashedalkhatib\datatables\DataTableAsset` your `$depends` array
    - Ex:

    ```
                public $depends = [
                  'yii\web\YiiAsset',
                  'yii\bootstrap\BootstrapAsset',
                  'yii\bootstrap\BootstrapPluginAsset',
                  'rashedalkhatib\datatables\DataTableAsset'
          ];

    ```

Usage Example (PHP Widget)
--------------------------

[](#usage-example-php-widget)

### - application side

[](#--application-side)

```
$searchFormSelector = '#searchForm';
$ajaxUrl = Url::to(['api/yourEndPoint']); // Adjust the URL based on your routes

// Define your DataTable columns
$columns = [
    [
        'title' => 'ID',
        'data' => 'id',
        'visible' => true,
        'render' => new JsExpression('function(data, type, row) {
            return "demo";
        }'),
    ],
];

// Configure other DataTable parameters
$processing = true;
$serverSide = true;
$pageLength = 10;
$dom = 'Btip';
$buttons = [
    [
        'extend' => 'excel',
        'text' => 'Excel',
        'titleAttr' => 'Excel',
        'action' => new JsExpression('exportAll') // this is required
    ],
];

// Configure Ajax settings
$ajaxConfig = [
    'url' => $ajaxUrl,
    'bdestroy' => true,
    'type' => 'POST',
    'data' => new JsExpression('function(d) {
            var searchForm = $('body').find('#searchForm').serializeArray();

            searchForm[searchForm.length] = { name: 'YourModel[page]', value: d.start }; // required
            searchForm[searchForm.length] = { name: 'YourModel[length]', value: d.length }; // required
            searchForm[searchForm.length] = { name: 'YourModel[draw]', value: d.draw }; // required

            var order = {
                'attribute': d.columns[d.order[0]['column']]['data'],
                'dir': d.order[0]['dir']
            }; // required

            searchForm[searchForm.length] = { name: 'YourModel[order]', value: JSON.stringify(order) };
            return searchForm;
    }'),
    'dataSrc' => new JsExpression('function(d) {
        var searchForm = $("' . $searchFormSelector . '").serializeArray();
        if (d.validation) {
            searchForm.yiiActiveForm("updateMessages", d.validation, true);
            return [];
        }
        return d.data;
    }'),
];

// Use the DataTableWidget with configured parameters
DataTable::widget([
    'id' => 'yourDataTable',
    'ajaxConfig' => $ajaxConfig,
    'columns' => $columns,
    'processing' => $processing,
    'serverSide' => $serverSide,
    'pageLength' => $pageLength,
    'dom' => $dom,
    'buttons' => $buttons,
]);

// The HTML container for your DataTable
echo '// your inputs ';
echo '';

```

Usage Example (Java Script)
---------------------------

[](#usage-example-java-script)

### - application side

[](#--application-side-1)

#### front end

[](#front-end)

```

// your inputs

```

```
var arrayToExport = [0,1];
$('#yourDataTable').DataTable({
    "ajax": {
        // Server-side processing configuration
        "url": "../api/yourEndPoint",
        "bdestroy": true, // this allows you to re init the dataTabel and destory it
        "type": "POST", // request method
        "data": function (d) { // this represent the data you are sending with your ajax request
            // Custom function for sending additional parameters to the server
            var searchForm = $('body').find('#searchForm').serializeArray();

            searchForm[searchForm.length] = { name: "YourModel[page]", value: d.start }; // required
            searchForm[searchForm.length] = { name: "YourModel[length]", value: d.length }; // required
            searchForm[searchForm.length] = { name: "YourModel[draw]", value: d.draw }; // required

            var order = {
                'attribute': d.columns[d.order[0]['column']]['data'],
                'dir': d.order[0]['dir']
            }; // required

            searchForm[searchForm.length] = { name: "YourModel[order]", value: JSON.stringify(order) };
            return searchForm;
        },
        dataSrc: function (d) {
            // Custom function to handle the response data
            // EX:
            var searchForm = $('body').find('#searchForm').serializeArray();
            if (d.validation) {
                searchForm.yiiActiveForm('updateMessages', d.validation, true);
                return [];
            }
            return d.data;
        }
    },
    "columns": [{
        // Column configurations
        "title": "ID",
        "data": "id",
        "visible": true // visablity of column
    },
    // ... (other columns)
    {
        "title": "Actions",
        "data": "id",
        "visible": actionCol,
        "render": function (data, type, row) {
            // Custom rendering function for the "Actions" column
            return 'View';
        }
    }],
    processing: true,
    serverSide: true,
    "pageLength": 10,
    dom: "Btip",
    "buttons": [{
        // "Excel" button configuration
        "extend": 'excel',
        exportOptions: {
            columns: arrayToExport
        },
        "text": '  Excel',
        "titleAttr": 'Excel',
        "action": exportAll // newexportaction this action is to allow you exporting with server side without rendaring data
    }],
});
```

### application back end

[](#application-back-end)

#### these params should be sent to the API

[](#these-params-should-be-sent-to-the-api)

```
// in your HTTP request you want to include these params
   $_postData = [
   'page' => $this->page == 0 ? 0 : $this->page / $this->length, // this equation is required to handle Yii2 Data provider Logic
   'limit' => $this->length,
   'export' => $this->export,
   'order' => $this->order,
   // add your custom params .....
   ];

```

#### these params should be returned to the Datatable endpoint

[](#these-params-should-be-returned-to-the-datatable-endpoint)

```
return $this->asJson(
                    [
                        'data' => $_scoreData->data,
                        'draw' => $_scoreSearchForm->draw,
                        'recordsTotal' => $_scoreData->count,
                        'recordsFiltered' => $_scoreData->count
                ]);

```

Usage API Side
--------------

[](#usage-api-side)

#### yourEndPoint action

[](#yourendpoint-action)

```
    public function actionYourEndPoint()
    {

        $searchModel = new SearchModel();

        $dataProvider = $searchModel->search(Yii::$app->request->get());
        return $this->asJson(
            array(
                'data' => $dataProvider['data'],
                'count' => $dataProvider['count']
            )
        );

    }

```

#### search function

[](#search-function)

```
    public function search($params)
    {
        $this->load($params, ''); // load your values into the model
        $query = Data::find(); // Data model is your link to the database

        $_order = json_decode($this->order);
        if ($this->export == 'true') {
            $dataProvider = new ActiveDataProvider([
                'query' => $query
                // we removed the page and pageSize keys to allow all data to be exported
            ]);
        } else {
            $_orderType = SORT_ASC;
            if ($_order->dir == 'desc')
                $_orderType = SORT_DESC;
            $query->orderBy([$_order->attribute => $_orderType]);
            $dataProvider = new ActiveDataProvider([
                'query' => $query,
                'pagination' => [
                    'pageSize' => $this->limit,
                    'page' => $this->page,
                ],
            ]);
        }

        return array(
            'data' => $dataProvider->getModels(),
            'count' => $dataProvider->getTotalCount()
        );
    }

```

Feel Free to contact me :
-----------------------------------------------------

[](#feel-free-to-contact-me--alkhatibrashedgmailcom)

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 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.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

749d ago

### Community

Maintainers

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

---

Top Contributors

[![RashedAlkhatib](https://avatars.githubusercontent.com/u/66955170?v=4)](https://github.com/RashedAlkhatib "RashedAlkhatib (22 commits)")

---

Tags

javascriptlibraryjquerydatatablesyii2extensiontable

### Embed Badge

![Health badge](/badges/rashedalkhatib-yii2-datatables/health.svg)

```
[![Health](https://phpackages.com/badges/rashedalkhatib-yii2-datatables/health.svg)](https://phpackages.com/packages/rashedalkhatib-yii2-datatables)
```

###  Alternatives

[fedemotta/yii2-widget-datatables

DataTables widget for Yii2

34179.4k1](/packages/fedemotta-yii2-widget-datatables)[richardfan1126/yii2-js-register

Yii2 widget to register JS into view

1357.2k7](/packages/richardfan1126-yii2-js-register)

PHPackages © 2026

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