Yii2:使用 kartik\gridview 在 table 顶部添加空行

Yii2 : Add empty row at the top of the table using kartik\gridview

我正在尝试使用 yii2-kartik\gridview 在 table 的顶部插入一个空行,以便我可以向每一列添加自定义组件。

我希望打印出来的结果如下:

到目前为止,我只设法通过添加 filterModel:

来插入这一行
<?php
    $gridViewPesquisaPonto = GridView::widget([
        'moduleId' => 'gridview',
        'dataProvider' => $pesquisaPontodataProvider,
        'filterModel' => true, // The table row containing the filters is configured here
        'layout' => "{items}{summary}{pager}",
        'captionOptions' => ['class' => 'text-wrap'],
        'options' => [
            'id' => 'grid-pontos-pesquisa',
        ],
        'columns' => [
            // ...

然而,这一行是专供gridview实现的过滤器使用的。我想知道一种插入一行的方法,以便我可以自由编辑它(如果您有包含此答案的文档的 link,请在答案中 post,因为我没有'还没找到)。

您可以使用 GridViewbeforeRow 选项,它需要一个闭包

function ($model, $key, $index, $grid)

其中

  • $model: 当前正在渲染的数据模型
  • $key: 当前数据模型关联的键值
  • $index:[[dataProvider]]
  • 返回的模型数组中数据模型从零开始的索引
  • $gridGridView 对象

您可以使用 $index 来确定它是否是第一行并添加您的自定义行,如下所示

'beforeRow'=>function ($model, $key, $index, $grid){
    if($index===0){
        return "<tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        </tr>";
    }

},

记得添加或减少 <td> 列以匹配 gridview 中的列数。

我将用这个来扩展 Muhammad Omer Aslam 的回答。我想这会更动态,不需要一直调整需要显示的列数。

您可以使用 GridViewbeforeRow 选项,它需要一个闭包

function ($model, $key, $index, $grid)

所以在这里我们可以抓取所有模型属性,甚至在显示之前检查它们

'beforeRow'=>function ($model){
    $row = "<tr>";
    //loop thru attributes
    foreach($model->attributes as $key => $value){
        $row .= "<td>" . $key . "</td>";
    }
    return $row .= "</tr>";
},

希望对您有所帮助。