我建议你覆盖 GridView 的 renderTableRow。如果您在要分组的列上检测到值更改,只需插入自定义组标题行。
<?php
class GroupGridView extends \yii\grid\GridView
{
public $groupingColumn = null;
public $groupingText = null;
public function renderTableRow ($model, $key, $index)
{
if ($this->groupingColumn == null)
return parent::renderTableRow($model, $key, $index);
$models = $this->dataProvider->models;
$result = '';
if ($index < count($models) - 1 && ($index == 0 || $models[$index][$this->groupingColumn] != $models[$index + 1][$this->groupingColumn])) {
$result = sprintf('<tr class="grouping"><td colspan="%d">%s</td></tr>', count($this->columns), ($this->groupingText == null ? $models[$index]->{$this->groupingColumn} : (is_callable($this->groupingText) ? call_user_func($this->groupingText, $model, $key, $index) : $this->groupingText)));
}
return $result . parent::renderTableRow($model, $key, $index);
}
}
$dataProvider = new \yii\data\ActiveDataProvider([
'query' => \common\models\Task::find()->orderBy(['customer_id' => SORT_ASC]),
'pagination' => [
'pageSize' => 100,
],
]);
echo GroupGridView::widget([
'groupingColumn' => 'item',
'groupingText' => function($model, $key, $index) {
return sprintf('--- %s --- %s --- %d', $model->item, $key, $index);
},
'dataProvider' => $dataProvider
])
?>
请记住,您必须按分组列进行排序。