Search code examples
gridviewyii2kartik-v

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


I'm trying to insert an empty row at the top of the table with the yii2-kartik\gridview, so that I can add custom components to each column.

I would like the result to be as follows in the print:

enter image description here So far I've only managed to insert this line by adding the 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' => [
            // ...

However, this line is exclusive for the use of filters implemented by the gridview. I would like to know a way to insert a line so that I can edit it freely (If you have the link to the documentation that contains this answer, please post in the answer, as I haven't found it yet).


Solution

  • You can use the beforeRow option of the GridView which takes a closure

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

    where

    • $model: the current data model being rendered
    • $key: the key value associated with the current data model
    • $index: the zero-based index of the data model in the model array returned by [[dataProvider]]
    • $grid: the GridView object

    You can use the $index to identify if its the first row and add your custom row like below

    '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>";
        }
    
    },
    

    Remember to add or reduce the <td> columns to match the number of columns in your gridview.