Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Yii2 Widget for DataTables jQuery plug-in

License

NotificationsYou must be signed in to change notification settings

NullRefExcep/yii2-datatables

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

97 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Yii2 Widget forDataTables 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 yourcomposer.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 ourMigration Guide for detailed instructions.

Basic Usage

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

For backwards compatibility the old usage viadata is still supported

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

DataTable options

Also you can use allDatatables 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 ofLinkColumn:

  • label - text placed ina tag;
  • title - header title of column;
  • url - will be passed toUrl::to();
  • linkOptions - HTML options of thea tag;
  • queryParams - array of params added tourl,['id'] by default;
  • render - custom render js function. E.g:
//config ...'columns' => [//...        ['class' =>'nullref\datatable\LinkColumn','queryParams' => ['some_id'],'render' =>newJsExpression('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 toqueryParams property

Column filtering

You can add column filtering functionality by setting optionwithColumnFilter totrue :

  • By default it generates a text field as filter input.
  • It can be replaced by a combo box usingfilter parameter when defining column. It should be a associative arraywhere key is used as filter (value sent to server) and value for cell rendering
  • It can be avoided by settingfilter 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 foractive field sent to server will contains'true' or'false' but the cell contentwill be'Yes' or'No' and the filter will be rendered as a combo box.

No filter will be generated forlast_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, includingBootstrap,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 usingtableOptions 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 addDataTableAction to controller like this:

class SomeControllerextends Controller{publicfunctionactions()    {return ['datatables' => ['class' =>'nullref\datatable\DataTableAction','query' => Model::find(),            ],        ];    }}

Searching and ordering can be customized using closures

publicfunctionactions(){return ['datatables' => ['class' =>'nullref\datatable\DataTableAction','query' => Model::find(),'applyOrder' =>function($query,$columns,$order) {//custom ordering logic$orderBy = [];foreach ($orderas$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 ($columnsas$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 calljoin or similar methods from$query inapplyFilter closure.

You may also specify a closure forquery inDataTableAction 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 passextraColumns 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' =>newJsExpression($customColumnRender),        ],    ],])?>
class SomeControllerextends Controller{publicfunctionactions()    {return ['datatables' => ['class' =>'nullref\datatable\DataTableAction','query' => Model::find(),'extraColumns' => ['customPrice'],            ],        ];    }}
<?= \nullref\datatable\DataTable::widget([/** ... */'extraColumns' => ['customPrice'],])?>

About

Yii2 Widget for DataTables jQuery plug-in

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors12

Languages


[8]ページ先頭

©2009-2025 Movatter.jp