Yii2 + ZUI 数据表格②的使用

根据官方文档:

<!-- 引入css样式 -->
<link rel="stylesheet" href="zui/css/zui.css" />
<link rel="stylesheet" href="zui/lib/datagrid/zui.datagrid.css" />

<!-- 引入js文件 -->
<script type="text/javascript" src="js/jquery-2.2.4.min.js" ></script>
<script type="text/javascript" src="zui/js/zui.min.js" ></script>
<script type="text/javascript" src="zui/lib/datagrid/zui.datagrid.min.js" ></script>

<!-- HTML -->
<div id="datagridExample" class="datagrid datagrid-striped">
	<div class="datagrid-container"></div>
	<div class="pager"></div>
</div>

<!-- js -->
<script>
$('#datagridExample').datagrid({
    dataSource: {
        remote: 'http://yii2advanced.ccc/article/datagrid.html',
        cols: [
            {name: 'id', label: 'ID'},
            {name: 'title', label: '标题'}
        ]
    },
    states: {
        pager: {page: 1, recPerPage: 10}
    },
    height: 'page',
    checkable: true,  // 行选择
});
</script>

服务器端:

$dataProvider = new ActiveDataProvider([
    'query' => Article::find(),
    'pagination' => [
        'pageSize' => 10,
    ],
]);
$data = [];
foreach($dataProvider->getModels() as $model){
    $data[] = [
        'id' => $model->id,
        'title' => $model->title,
    ];
}
$responseData = [
    'result' => 'success',
    'data' => $data,
    'message' => '未获取到数据',
    'pager' => [
        'page' => $dataProvider->pagination->page + 1,  // 重点
        'recTotal' => $dataProvider->totalCount,
        'recPerPage' => $dataProvider->pagination->pageSize,
    ],
];
return $this->asJson($responseData);

意事项:

Yii的yii\data\Pagination::page属性默认从0开始,所以,返回的页码总是比请求的页码小1。

比如请求第6页,Pagination::page返回页码为5,datagrid插件就会再次请求第5页,一直请求到第0页。

测试发现:如果Pagination::page + 1,则会向上请求,从第6页一直请求到第13页(本例只有123条数据)甚至更高的值。


数据表格中的按钮:

$('#datagridExample').datagrid({
    dataSource: {
        remote: 'http://yii2advanced.ccc/article/datagrid.html',
        cols: [
            {name: 'id', label: 'ID'},
            {name: 'title', label: '标题'},
            {name: 'operation', label: '按钮', html: true, valueOperator: {
                getter: function(dataValue, cell, dataGrid){
                    //console.log(cell.config.data.id);
                    var buttons = '<a href="article/create?id=' + cell.config.data.id +  '">更新</a> ';
                    buttons += '<a href="article/delete?id=' + cell.config.data.id +  '">删除</a>';
                    return buttons;
                }
            }},
        ]
    },
});