承接 nullref/yii2-datatables 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

nullref/yii2-datatables

Composer 安装命令:

composer require nullref/yii2-datatables

包简介

Yii2 Extension for DataTables jQuery plug-in

README 文档

README

Yii2 Widget for DataTables plug-in for jQuery

Installation

The preferred way to install this extension is through composer.

Either run

composer require nullref/yii2-datatables

or add

"nullref/yii2-datatables": "~2.0"

to the require section of your composer.json file.

⚠️ Version 2.0 Requirements

  • PHP: >= 7.4.0
  • Yii2: >= 2.0.50
  • DataTables: v2.0 (automatically installed via NPM assets)

📋 Upgrading from v1.x

If you're upgrading from version 1.x, please see our Migration Guide for detailed instructions.

Basic Usage

<?= \nullref\datatable\DataTable::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        'name',
        'email'
    ],
]) ?>

For backwards compatibility the old usage via data is still supported

<?= \nullref\datatable\DataTable::widget([
    'data' => $dataProvider->getModels(),
    'columns' => [
        'id',
        'name',
        'email'
    ],
]) ?>

DataTable options

Also you can use all Datatables options

To pass them as widget options:

<?= \nullref\datatable\DataTable::widget([
    'data' => $dataProvider->getModels(),
    'scrollY' => '200px',
    'scrollCollapse' => true,
    'paging' => false,
    'columns' => [
        'name',
        'email'
    ],
    'withColumnFilter' => true,
]) ?>

Specifies header label and css class for cell

    <?= \nullref\datatable\DataTable::widget([
        'columns' => [
            //other columns
            [
                'data' => 'active',
                'title' => 'Is active',
                'sClass' => 'active-cell-css-class',
            ],
        ],
    ]) ?>

Specifies datatable id

<?= \nullref\datatable\DataTable::widget([
    'data' => $dataProvider->getModels(),
    'id' => 'your-datatable-id'
]) ?>

Add Links to row

    <?= \nullref\datatable\DataTable::widget([
        'columns' => [
            //other columns
            [
                'class' => 'nullref\datatable\LinkColumn',
                'url' => ['/model/delete'],
                'linkOptions' => ['data-confirm' => 'Are you sure you want to delete this item?', 'data-method' => 'post'],
                'label' => 'Delete',
            ],
        ],
    ]) ?>

Properties of LinkColumn:

  • label - text placed in a tag;
  • title - header title of column;
  • url - will be passed to Url::to();
  • linkOptions - HTML options of the a tag;
  • queryParams - array of params added to url, ['id'] by default;
  • render - custom render js function. E.g:
//config ...
    'columns' => [
        //...
        [
            'class' => 'nullref\datatable\LinkColumn',
            'queryParams' => ['some_id'],
            'render' => new JsExpression('function render(data, type, row, meta ){
                return "<a href=\"/custom/url/"+row["some_id"]+"\">View</a>"
            }'),
        ],
    ],
//...

You should pass fields that are using at render function to queryParams property

Column filtering

You can add column filtering functionality by setting option withColumnFilter to true :

  • By default it generates a text field as filter input.
  • It can be replaced by a combo box using filter parameter when defining column. It should be a associative array where key is used as filter (value sent to server) and value for cell rendering
  • It can be avoided by setting filter to false
    <?= \nullref\datatable\DataTable::widget([
        'columns' => [
            'id',
            //...
            [
                'data' => 'active',
                'title' => \Yii::t('app', 'Is active'),
                'filter' => ['true' => 'Yes', 'false' => 'No'],
            ],
            [
                'data' => 'last_connection',
                'filter' => false,
            ],
        ],
    ]) ?>
//...

In this example above, filter for active field sent to server will contains 'true' or 'false' but the cell content will be 'Yes' or 'No' and the filter will be rendered as a combo box.

No filter will be generated for last_connection attrribute.

Advanced column definition

Cell rendering or filter can be customized using \nullref\datatable\DataTableColumn class.

    <?= \nullref\datatable\DataTable::widget([
        'columns' => [
            //other columns
            [
                'class' => 'nullref\datatable\DataTableColumn', // can be omitted
                'data' => 'active',
                'renderFiler' => new \yii\web\JsExpression('function() { ' .
                    'return jQuery(\'<input type="checkbox" value="true"/> Active only\'); ' .
                '}'),
                'render' => new \yii\web\JsExpression('function(data, type, row, meta) { ' .
                    'return jQuery(\'<input type="checkbox" value="true" disabled/>\')' .
                    '    .prop(\'checked\', data == \'true\'); ' .
                    '}'),
            ],
        ],
    ]) ?>

Styling

DataTables supports several styling solutions, including Bootstrap, jQuery UI, Foundation.

'assetManager' => [
    'bundles' => [
        'nullref\datatable\assets\DataTableAsset' => [
            'styling' => \nullref\datatable\assets\DataTableAsset::STYLING_BOOTSTRAP,
        ]
    ],
],

Bootstrap

Bootstrap tables require the class 'table', so you'll need to add the 'table' class using tableOptions via the widget config.

<?= \nullref\datatable\DataTable::widget([
    'data' => $dataProvider->getModels(),
    'tableOptions' => [
        'class' => 'table',
    ],
    'columns' => [
        'id',
        'name',
        'email',
    ],
]) ?>

Custom assets

It's possible to use custom styles and scripts:

'nullref\datatable\assets\DataTableAsset' => [
    'sourcePath' => '@webroot/js/plugin/datatables/',
    'js' => [
        'jquery.dataTables-1.10-cust.js',
        'DT_bootstrap.js',
    ],
    'css' => [
        'data-table.css',
    ],
    'styling' => false,
]

Server-side processing

To enable server-side processing add DataTableAction to controller like this:

class SomeController extends Controller
{
    public function actions()
    {
        return [
            'datatables' => [
                'class' => 'nullref\datatable\DataTableAction',
                'query' => Model::find(),
            ],
        ];
    }
}

Searching and ordering can be customized using closures

public function actions()
{
    return [
         'datatables' => [
             'class' => 'nullref\datatable\DataTableAction',
             'query' => Model::find(),
             'applyOrder' => function($query, $columns, $order) {
                //custom ordering logic
                $orderBy = [];
                foreach ($order as $orderItem) {
                    $orderBy[$columns[$orderItem['column']]['data']] = $orderItem['dir'] == 'asc' ? SORT_ASC : SORT_DESC;
                }
                return $query->orderBy($orderBy);
             },
             'applyFilter' => function($query, $columns, $search) {
                //custom search logic
                $modelClass = $query->modelClass;
                $schema = $modelClass::getTableSchema()->columns;
                foreach ($columns as $column) {
                    if ($column['searchable'] == 'true' && array_key_exists($column['data'], $schema) !== false) {
                        $value = empty($search['value']) ? $column['search']['value'] : $search['value'];
                        $query->orFilterWhere(['like', $column['data'], $value]);
                    }
                }
                return $query;
             },
         ],
    ];
}

If you need to get some relation data you can call join or similar methods from $query in applyFilter closure.

You may also specify a closure for query in DataTableAction config if you need complex query like in the following code:

/** ... */
'query' => function() {
    $calculatedValue = calculate_value_for_query();
    
    return Model::find()->where(['calculated_value' => $calculatedValue]);
},
/** ... */

And add options to widget:

<?= \nullref\datatable\DataTable::widget([
    /** ... */
    'serverSide' => true,
    'ajax' => '/site/datatables',
]) ?>

Extra columns

If need to use some custom fields from your model at your render function at column you could pass extraColumns param.

It available at DataTable widget, column and server side action definition:

<?= \nullref\datatable\DataTable::widget([
    /** ... */
    'data' => $dataProvider->getModels(),
    'extraColumns' => ['customPrice'],
    'columns' => [
        [
            'title' => 'Custom column',
            'extraColumns' => ['customField'],
            'render' => new JsExpression($customColumnRender),
        ],
    ],
]) ?>
class SomeController extends Controller
{
    public function actions()
    {
        return [
            'datatables' => [
                'class' => 'nullref\datatable\DataTableAction',
                'query' => Model::find(),
                'extraColumns' => ['customPrice'],
            ],
        ];
    }
}
<?= \nullref\datatable\DataTable::widget([
    /** ... */
    'extraColumns' => ['customPrice'],
]) ?>

nullref/yii2-datatables 适用场景与选型建议

nullref/yii2-datatables 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 92.68k 次下载、GitHub Stars 达 72, 最近一次更新时间为 2014 年 12 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「jquery」 「plugin」 「yii」 「widget」 「datatables」 「datatable」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 nullref/yii2-datatables 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 nullref/yii2-datatables 我们能提供哪些服务?
定制开发 / 二次开发

基于 nullref/yii2-datatables 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 92.68k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 72
  • 点击次数: 30
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 72
  • Watchers: 11
  • Forks: 47
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2014-12-10