Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads Daily Downloads
Thankful to Krajee!
to get more out of us.

NOTE: This extension depends on the kartik-v/yii2-krajee-base extension which in turn depends on the yiisoft/yii2-bootstrap extension. Check the composer.json for this extension's requirements and dependencies that may be updated by composer.

Yii2 GridView on steroids. A module with various modifications and enhancements to one of the most used widgets by Yii developers. The widget contains new additional Grid Columns with enhanced settings for Yii Framework 2.0. The widget also incorporates various Bootstrap 3.x styling options and has embedded support for Pjax based rendering. View a complete demo.

Prerequisites

Note

You must read this web tip / wiki on setting the minimum-stability settings for your application's composer.json.
Install

The preferred way to install this extension is through composer. Either run:

$ php composer.phar require kartik-v/yii2-grid "@dev"

or add:

"kartik-v/yii2-grid": "@dev"

to the require section of your composer.json file. Then run:

php composer.phar update

to get the updated package on your application install.

The extension has been created as a module to enable access to advanced features like download actions (exporting as csv, text, html, xls, pdf, or json). Before using any of the functions, you must add the module to your configuration file. The module must be named gridview as shown below:

'modules' => [
   'gridview' =>  [
        'class' => '\kartik\grid\Module'
        // enter optional module parameters below - only if you need to  
        // use your own export download action or custom translation 
        // message source
        // 'downloadAction' => 'gridview/export/download',
        // 'i18n' => []
    ]
];
The module can take in the following parameters:
  • downloadAction: mixed, the action (url) used for downloading exported file. Defaults to 'gridview/export/download'.

  • i18n: array, the internalization configuration for this module. Defaults to:

    [
        'class' => 'yii\i18n\PhpMessageSource',
        'basePath' => '@kvgrid/messages',
        'forceTranslation' => true
    ];
    

Note:

The module has i18n / translation features enabled. You can edit the kvgrid.php file in the messages folder for your language by submitting a new pull request.

The GridView widget contains various modifications and enhancements as described below:

Control various options to style your grid table. The following parameters are additionally recognized over and above the configuration options in the base Yii GridView widget:

  • bootstrap: boolean, whether the grid view will have a Bootstrap table styling. Defaults to true. If set to false, will automatically disable/remove all Bootstrap specific markup from the grid table and filters.

  • bordered: boolean, whether the grid table will have a bordered style. Applicable only if bootstrap is true. Defaults to true.

  • striped: boolean, whether the grid table will have a striped style. Applicable only if bootstrap is true. Defaults to true.

  • condensed: boolean, whether the grid table will have a condensed style. Applicable only if bootstrap is true. Defaults to false.

  • responsive: boolean, whether the grid table will have a responsive style. Applicable only if bootstrap is true. Defaults to true.

  • responsiveWrap: boolean, whether the grid table columns will be responsively wrapped to a single column for small screen devices (less than 480px). Defaults to true.

  • hover: boolean, whether the grid table will highlight row on hover. Applicable only if bootstrap is true. Defaults to false.

  • containerOptions: array|boolean, the HTML attributes for the grid container. The grid table items will be wrapped in a div container with the configured HTML attributes. The ID for the container will be auto generated. When you set the responsive property to true, a CSS class of table-responsive will be automatically added to the container.

  • perfectScrollbar: boolean, whether pretty perfect scrollbars using perfect scrollbar plugin is to be used.Defaults to false. If this is set to true, the floatOverflowContainer property will be auto set to true, if floatHeader is true.

  • perfectScrollbarOptions: array, he plugin options for the perfect scrollbar plugin. Refer the perfect scrollbar plugin documentation for details on options that can be set.

The following base GridView parameters can be used with the extended GridView and have certain defaults preset.

  • tableOptions: array, HTML attributes for the grid table element. This is auto generated based on the above settings.

  • footerRowOptions: array, HTML attributes for the table footer row. Defaults to ['class' => 'kv-table-footer']

  • captionOptions: array, HTML attributes for the table caption. Defaults to ['class' => 'kv-table-caption']

  • headerRowOptions: array, HTML attributes for the table header row.

  • rowOptions: array, HTML attributes for each table row. You can set this to apply specific classes to the row. For example you can set a Bootstrap Contextual class to highlight the row like: 'rowOptions' => ['class' => GridView::TYPE_DANGER]

Usage

use kartik\grid\GridView;

// Generate a bootstrap responsive striped table with row highlighted on hover
echo GridView::widget([
    'dataProvider'=> $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'responsive'=>true,
    'hover'=>true
]);

With release v1.9.0, the Yii GridView widget now supports rendering via Pjax by default. The following properties help one control the Pjax behavior:

  • pjax: boolean, whether the grid view will be rendered within a pjax container. Defaults to false. If set to true, the entire GridView widget will be parsed via Pjax and rendered inside a yii\widgets\Pjax widget container. If set to false, pjax will be disabled and none of the pjax settings will be applied.

  • pjaxSettings: array, the various pjax configuration settings for the widget. This will be considered only when pjax is set to true. The following settings are recognized:

    • neverTimeout: boolean, whether the pjax request should never timeout. Defaults to true. The pjax:timeout event will be configured to disable timing out of pjax requests for the pjax container.

    • options: array, the options for the yii\widgets\Pjax widget. The pjax container identifier is read via pjaxSettings['options']['id'] . You could override and manually set pjaxSettings['options']['id'] if you need your own pjax container identifier. If not set this defaults to:

      $grid->options['id'] . '-pjax'
      

      where $grid->options refer to the widget's options property.

    • loadingCssClass: boolean/string, the CSS class to be applied to the grid when loading via pjax. If set to false - no css class will be applied. If it is empty, null, or set to true, will default to kv-grid-loading.

    • beforeGrid: string, any content to be embedded within pjax container before the Grid widget.

    • afterGrid: string, any content to be embedded within pjax container after the Grid widget.

Usage

use kartik\grid\GridView;

// Control your pjax options
echo GridView::widget([
    'dataProvider'=> $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'pjax'=>true,
    'pjaxSettings'=>[
        'neverTimeout'=>true,
        'beforeGrid'=>'My fancy content before.',
        'afterGrid'=>'My fancy content after.',
    ]
]);

The extended gridview provides you with ability to add additional header and footer rows. Use the following properties to control the configuration of these rows:

  • beforeHeader: array|string, configuration of additional header table rows that will be rendered before the default grid header row. If set as a string, it will be displayed as is, without any HTML encoding. If set as an array, each row in this array corresponds to a HTML table row, where you can configure the columns with these properties:

    • columns: array, the header row columns configuration where you can set the following properties:

      • content: string, the table cell content for the column.

      • tag: string, the tag for rendering the table cell. If not set, defaults to th.

      • options: array, the HTML attributes for the table cell.

    • options: array, the HTML attributes for the table row.

  • afterHeader: array|string, configuration of additional header table rows that will be rendered after the default grid header row. If set as a string, it will be displayed as is, without any HTML encoding. If set as an array, each row in this array corresponds to a HTML table row, where you can configure the columns with these properties:

    • columns: array, the header row columns configuration where you can set the following properties:

      • content: string, the table cell content for the column.

      • tag: string, the tag for rendering the table cell. If not set, defaults to th.

      • options: array, the HTML attributes for the table cell.

    • options: array, the HTML attributes for the table row.

  • beforeFooter: array|string, configuration of additional footer table rows that will be rendered before the default grid footer row. If set as a string, it will be displayed as is, without any HTML encoding. If set as an array, each row in this array corresponds to a HTML table row, where you can configure the columns with these properties:

    • columns: array, the footer row columns configuration where you can set the following properties:

      • content: string, the table cell content for the column.

      • tag: string, the tag for rendering the table cell. If not set, defaults to th.

      • options: array, the HTML attributes for the table cell.

    • options: array, the HTML attributes for the table row.

  • afterFooter: array|string, configuration of additional footer table rows that will be rendered after the default grid footer row. If set as a string, it will be displayed as is, without any HTML encoding. If set as an array, each row in this array corresponds to a HTML table row, where you can configure the columns with these properties:

    • columns: array, the footer row columns configuration where you can set the following properties:

      • content: string, the table cell content for the column.

      • tag: string, the tag for rendering the table cell. If not set, defaults to th.

      • options: array, the HTML attributes for the table cell.

    • options: array, the HTML attributes for the table row.


The enhanced grid from Krajee allows resizing of the columns just like a spreadsheet (since v3.0.0). This uses the JQuery ResizableColumns plugin for resize and store.js for localStorage persistence. The following options help you to control the resizable settings:

  • resizableColumns: boolean, whether to allow resizing of columns. Defaults to true.

  • persistResize: boolean, whether to store resized column state using local storage persistence (supported by most modern browsers). Defaults to false.

  • hideResizeMobile: boolean, whether to hide resizable columns for smaller screen sizes (< 768px). Defaults to true. When this is true, it will make the screen layout responsive for smaller screen devices (< 768px) and not allow content to overflow the page.

  • resizableColumnsOptions: array, plugin options for resizable columns. Refer the plugin documentation for details on what options can be set here.

  • resizeStorageKey: string, resizable unique storage prefix to append to the grid id. If empty or not set it will default to Yii::$app->user->id.

Usage

use kartik\grid\GridView;

// Generate a floating header fixed to top and an offset of 50 px 
// from top of the page for the bootstrap navbar
echo GridView::widget([
    'dataProvider'=> $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'resizableColumns'=>true,
    'resizeStorageKey'=>Yii::$app->user->id . '-' . date("m")
]);

Displays a floating header as you scroll the grid. Uses the JQuery Float THead plugin to display a seamless floating table header.

  • floatHeader: boolean, whether the grid table will have a floating table header. The floating behavior will only be applied if filterPostion is set to GridView::FILTER_POS_BODY or GridView::FILTER_POS_FOOTER. Defaults to false.

  • floatOverflowContainer: boolean, whether the table header will float and sticks around as you scroll within a container. If responsive is true then this is auto set to true. Defaults to false.

  • floatHeaderOptions: array, the plugin options for the floatThead plugin that would render the floating/sticky table header behavior. The default offset from the top of the window where the floating header will 'stick' when scrolling down is set to 50 assuming a fixed bootstrap navbar on top. You can set this to 0 or any javascript function/expression. Defaults to ['scrollingTop' => 50]. Check the plugin options for details.

Usage

use kartik\grid\GridView;

// Generate a floating header fixed to top and an offset of 50 px 
// from top of the page for the bootstrap navbar
echo GridView::widget([
    'dataProvider'=> $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'floatHeader'=>true,
    'floatHeaderOptions'=>['scrollingTop'=>'50']
]);

This is a new feature added to the GridView widget. The page summary is an additional row above the footer - for displaying the summary/totals for the current GridView page. Calculating the page summary will be setup within the DataColumn or FormulaColumn settings, as described in the later sections. The following parameters are applicable to control this behavior.

  • showPageSummary: boolean, whether to display the page summary row for the grid view. Defaults to false.

  • pageSummaryRowOptions: array, HTML attributes for the page summary row. Defaults to ['class' => 'kv-page-summary warning'].

Usage

use kartik\grid\GridView;

// Create a panel layout for your GridView widget
echo GridView::widget([
    'dataProvider'=> $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'showPageSummary' => true
]);

The toolbar is new feature and more enhanced with release v2.1.0 of the GridView widget. The grid offers ability to configure toolbar for adding various actions. The default templates place the toolbar in the before section of the panel. The toolbar is by default styled using Bootstrap button groups. Some of the default actions like the export button can be easily appended to the toolbar by using the special tag `{export}`. With version v2.1.0, if you are using the yii2-dynagrid extension it automatically displays the personalize, sort, and filter buttons in the toolbar. The toolbar can be setup as a string or an array.

  • if set as a string, it will be rendered as is.

  • if set as an array, each line item will be considered as following

    • if the line item is setup as a string, it will be rendered as is

    • if the line item is an array it will be parsed for the following keys

      • content: string, the content to be rendered as a bootstrap button group. The following special variables are recognized and will be replaced:

        • {export}: string, which will render the $export menu button content.

        • {toggleData}: string, which will render the toggle button as configured in toggleDataOptions. This will allow user to toggle between all data and default paginated data.

      • options: array, the HTML attributes for the button group div container. By default the CSS class `btn-group` will be attached to this container.

Usage

use kartik\grid\GridView;
use yii\helpers\Html;

// Create a panel layout for your GridView widget
echo GridView::widget([
    'dataProvider'=> $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'toolbar' => [
        [
            'content'=>
                Html::button('<i class="glyphicon glyphicon-plus"></i>', [
                    'type'=>'button', 
                    'title'=>Yii::t('kvgrid', 'Add Book'), 
                    'class'=>'btn btn-success'
                ]) . ' '.
                Html::a('<i class="glyphicon glyphicon-repeat"></i>', ['grid-demo'], [
                    'class' => 'btn btn-default', 
                    'title' => Yii::t('kvgrid', 'Reset Grid')
                ]),
        ],
        '{export}',
        '{toggleData}'
    ]
]);

NOTE: As seen above, the special tags {export} and {toggleData} just need to be positioned appropriately in the toolbar. The HTML attribute options for export and toggle button group containers can be controlled via exportContainer and toggleDataContainer properties. For example to set the button group sizes to small in the toolbar you can configure the widget like shown below:

echo GridView::widget([
    'dataProvider'=> $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'toolbar' => [
        [
            'content'=>
                Html::button('<i class="glyphicon glyphicon-plus"></i>', [
                    'type'=>'button', 
                    'title'=>Yii::t('kvgrid', 'Add Book'), 
                    'class'=>'btn btn-success'
                ]) . ' '.
                Html::a('<i class="glyphicon glyphicon-repeat"></i>', ['grid-demo'], [
                    'class' => 'btn btn-default', 
                    'title' => Yii::t('kvgrid', 'Reset Grid')
                ]),
            'options' => ['class' => 'btn-group-sm']
        ],
        '{export}',
        '{toggleData}'
    ],
    'toggleDataContainer' => ['class' => 'btn-group-sm'],
    'exportContainer' => ['class' => 'btn-group-sm']
]);

This is a new feature added to the GridView widget. The following export file formats are supported:

  • HTML: Hyper Text Markup Language

  • CSV: Comma Separated Values

  • TEXT: Tab Delimited Text

  • EXCEL: Microsoft Excel 95+

  • PDF: Portable Document Format

  • JSON: Javascript Object Notation

The menu is by default displayed at the right of the toolbar in the before part of the panel. The following are new features added since release v1.6.0:

  • Ability to preprocess and convert column data to your desired value before exporting. There is a new property exportConversions that can be setup in GridView. For example, this currently is set as a default to convert the HTML formatted icons for BooleanColumn to user friendly text like Active or Inactive after export.

  • Hide any row or column in the grid by adding one or more of the following CSS classes:
    • skip-export: Will skip this element during export for all formats (html, csv, txt, xls, pdf, json).

    • skip-export-html: Will skip this element during export for html export format.

    • skip-export-csv: Will skip this element during export for csv export format.

    • skip-export-txt: Will skip this element during export for txt export format.

    • skip-export-xls: Will skip this element during export for xls (excel) export format.

    • skip-export-pdf: Will skip this element during export for pdf export format.

    • skip-export-json: Will skip this element during export for json export format.

    These CSS can be set virtually in any of the grid or column properties that control HTML attributes. For example headerOptions, contentOptions, beforeHeader, footerOptions etc.

Note:

The special variable {export} can be included in any of the templates for showing the export menu. Typically you can do it in one of the header/before/after/footer sections or in the grid layout. You can thus position and style the export menu as per you need.
You can configure the export menu and the button through these grid properties:

  • export: array|boolean, the grid export menu settings. Displays a Bootstrap button dropdown menu that allows you to export the grid as either html, csv, or excel. If set to false, will not be displayed. The following options can be set:

    • icon: string, the glyphicon suffix to be displayed before the export menu label. If set to an empty string, this will not be displayed. Defaults to 'export'.

    • label: string, the export menu label (this is not HTML encoded). Defaults to empty string.

    • showConfirmAlert: boolean, whether to show a confirmation alert dialog before download. This confirmation dialog will notify user about the type of exported file for download and to disable popup blockers. Defaults to true.

    • target: string, the target for submitting the export form, which will trigger the download of the exported file. Defaults to GridView::TARGET_POPUP. Must be one of the following:

      • GridView::TARGET_POPUP or _popup: whereby a popup window with download progress message is displayed.

      • GridView::TARGET_BLANK or _blank: whereby a new blank window is displayed and closed after download is finished.

      • GridView::TARGET_SELF or _self: no window is popped up in this case, but download is submitted on same page.

    • messages: array, the the configuration of various messages that will be displayed at runtime:

      • allowPopups: string, the message to be shown to disable browser popups for download. Defaults to Disable any popup blockers in your browser to ensure proper download..

      • confirmDownload: string, the message to be shown for confirming to proceed with the download. Defaults to Ok to proceed?.

      • downloadProgress: string, the message to be shown in a popup dialog when download request is triggered. Defaults to Generating file. Please wait....

      • downloadProgress: string, the message to be shown in a popup dialog when download request is completed. Defaults to All done! Click anywhere here to close this window, once you have downloaded the file..

    • header: string, the header for the grid page export dropdown. If set to empty string will not be displayed. Defaults to <li role="presentation" class="dropdown-header">Export Page Data</li>.

    • fontAwesome: boolean, whether to use font awesome file type icons. Defaults to false. If you set it to true, then font awesome icons css class will be applied instead of glyphicons.

      Note:

      You must load the font awesome CSS file in your view or layout for this icons to be properly rendered. The widget does not load FontAwesome assets or CSS by default.
    • itemsBefore: array, any additional items that will be merged / prepended before the export dropdown list. This should be similar to the items property as supported by \yii\bootstrap\ButtonDropdown widget. Note: the page export items will be automatically generated based on settings in the exportConfig property.

    • itemsAfter: array, any additional items that will be merged / appended after the export dropdown list. This should be similar to the items property as supported by \yii\bootstrap\ButtonDropdown widget. Note: the page export items will be automatically generated based on settings in the exportConfig property.

    • options: array, HTML attributes for the export menu button. Defaults to ['class' => 'btn btn-danger'].

    • encoding: string, the export output file encoding. If not set, defaults to utf-8.

    • menuOptions: array, HTML attributes for the export dropdown menu. Defaults to ['class' => 'dropdown-menu dropdown-menu-right']. This is to be set exactly as the options property for \yii\bootstrap\Dropdown widget.

  • exportConversions: array, configuration for conversion of defined patterns in the grid cells as a preprocessing before the gridview is formatted for export. Each array row must consist of the following two keys:

    • from: string, is the pattern to search for in each grid column's cells

    • to: string, is the string to replace the pattern in the grid column cells

    This defaults to

    [
        ['from'=>GridView::ICON_ACTIVE, 'to'=>Yii::t('kvgrid', 'Active')],
        ['from'=>GridView::ICON_INACTIVE, 'to'=>Yii::t('kvgrid', 'Inactive')]
    ]
    
  • exportConfig: array|boolean, the configuration for each export format above. The array keys must be the one of the constants:

    • GridView::HTML or 'html'

    • GridView::CSV or 'csv'

    • GridView::TEXT or 'txt'

    • GridView::EXCEL or 'xls'

    • GridView::PDF or 'pdf'

    • GridView::JSON or 'json'

    The array values for each of the above is a configuration array containing the following:

    • icon string, the he glyphicon or font-awesome name suffix to be displayed before the export menu item label. The font awesome icons will be used, if you have setup export['fontAwesome'] propery to true. to be displayed before the export menu item label. If set to an empty string, this will not be displayed. For glyphicons, it defaults to one of the 'floppy-' glyphicons available in bootstrap.

      Note:

      You must load the font awesome CSS file in your view or layout for this icons to be properly rendered.
    • iconOptions: array, HTML attributes for export menu icon.

    • label string, the label for the export format menu item displayed.

    • showHeader boolean, whether to show table header in the output. Defaults to true.

    • showPageSummary boolean, whether to show table page summary in the output. Defaults to true.

    • showFooter boolean, whether to show table footer in the output. Defaults to true.

    • showCaption boolean, whether to show table caption in the output. Defaults to true.

    • filename string, the base file name for the generated file. Defaults to 'grid-export'. This will be used to generate a default file name for downloading (extension will be one of csv, html, or xls - based on the format setting).

    • alertMsg string, the message alert prompt to show before saving. If this is empty or null it will not be displayed.

    • mime string, the mime type (for the file format) to be set before downloading.

    • options string, array, HTML attributes for each export menu item.

    • config array, the additional configuration settings that are specific to each file format/type. The following configuration options are read specific to each file type:

      • cssFile string, the css file that will be used in the exported HTML file. Defaults to https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css.

      • colDelimiter string, string, the the column delimiter string for TEXT and CSV downloads.

      • rowDelimiter string, string, the the row delimiter string for TEXT and CSV downloads.

      • worksheet string, the active worksheet name for the downloaded excel file.

      You could pass all configuration settings in array format, as required by the \kartik\mpdf\Pdf extension component. In addition, the following additional settings are recognized:

      • contentBefore string, any HTML formatted content that will be embedded in the PDF output before the grid.

      • contentAfter string, any HTML formatted content that will be embedded in the PDF output after the grid.

      • colHeads: array, the column heading names to be output in the json file. If not set, it will be autogenerated as "col-{i}", where {i} is the column index. If slugColHeads is set to true, the extension will attempt to autogenerate column heads based on table column heading, whereever possible.

      • slugColHeads: boolean, whether to auto-generate column identifiers as slugs based on the table column heading name. If the table column heading contains characters which cannot be slugified, then the extension will autogenerate the column name as "col-{i}".

      • jsonReplacer: array|JsExpression, the JSON replacer property - can be an array or a JS function created using JsExpression. Refer the JSON documentation for details on setting this property. This defaults to the following callback function which trims each data element if it is a string:

        function(k,v){return typeof(v)==='string'?$.trim(v):v}
        
      • indentSpace: int, pretty print json output and indent by number of spaces specified. Defaults to 4.

    The default exportConfig is setup as below:

    // $isFa below determines if export['fontAwesome'] property is set to true.
    $defaultExportConfig = [
        GridView::HTML => [
            'label' => Yii::t('kvgrid', 'HTML'),
            'icon' => $isFa ? 'file-text' : 'floppy-saved',
            'iconOptions' => ['class' => 'text-info'],
            'showHeader' => true,
            'showPageSummary' => true,
            'showFooter' => true,
            'showCaption' => true,
            'filename' => Yii::t('kvgrid', 'grid-export'),
            'alertMsg' => Yii::t('kvgrid', 'The HTML export file will be generated for download.'),
            'options' => ['title' => Yii::t('kvgrid', 'Hyper Text Markup Language')],
            'mime' => 'text/html',
            'config' => [
                'cssFile' => 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'
            ]
        ],
        GridView::CSV => [
            'label' => Yii::t('kvgrid', 'CSV'),
            'icon' => $isFa ? 'file-code-o' : 'floppy-open', 
            'iconOptions' => ['class' => 'text-primary'],
            'showHeader' => true,
            'showPageSummary' => true,
            'showFooter' => true,
            'showCaption' => true,
            'filename' => Yii::t('kvgrid', 'grid-export'),
            'alertMsg' => Yii::t('kvgrid', 'The CSV export file will be generated for download.'),
            'options' => ['title' => Yii::t('kvgrid', 'Comma Separated Values')],
            'mime' => 'application/csv',
            'config' => [
                'colDelimiter' => ",",
                'rowDelimiter' => "\r\n",
            ]
        ],
        GridView::TEXT => [
            'label' => Yii::t('kvgrid', 'Text'),
            'icon' => $isFa ? 'file-text-o' : 'floppy-save',
            'iconOptions' => ['class' => 'text-muted'],
            'showHeader' => true,
            'showPageSummary' => true,
            'showFooter' => true,
            'showCaption' => true,
            'filename' => Yii::t('kvgrid', 'grid-export'),
            'alertMsg' => Yii::t('kvgrid', 'The TEXT export file will be generated for download.'),
            'options' => ['title' => Yii::t('kvgrid', 'Tab Delimited Text')],
            'mime' => 'text/plain',
            'config' => [
                'colDelimiter' => "\t",
                'rowDelimiter' => "\r\n",
            ]
        ],
        GridView::EXCEL => [
            'label' => Yii::t('kvgrid', 'Excel'),
            'icon' => $isFa ? 'file-excel-o' : 'floppy-remove',
            'iconOptions' => ['class' => 'text-success'],
            'showHeader' => true,
            'showPageSummary' => true,
            'showFooter' => true,
            'showCaption' => true,
            'filename' => Yii::t('kvgrid', 'grid-export'),
            'alertMsg' => Yii::t('kvgrid', 'The EXCEL export file will be generated for download.'),
            'options' => ['title' => Yii::t('kvgrid', 'Microsoft Excel 95+')],
            'mime' => 'application/vnd.ms-excel',
            'config' => [
                'worksheet' => Yii::t('kvgrid', 'ExportWorksheet'),
                'cssFile' => ''
            ]
        ],
        GridView::PDF => [
            'label' => Yii::t('kvgrid', 'PDF'),
            'icon' => $isFa ? 'file-pdf-o' : 'floppy-disk',
            'iconOptions' => ['class' => 'text-danger'],
            'showHeader' => true,
            'showPageSummary' => true,
            'showFooter' => true,
            'showCaption' => true,
            'filename' => Yii::t('kvgrid', 'grid-export'),
            'alertMsg' => Yii::t('kvgrid', 'The PDF export file will be generated for download.'),
            'options' => ['title' => Yii::t('kvgrid', 'Portable Document Format')],
            'mime' => 'application/pdf',
            'config' => [
                'mode' => 'c',
                'format' => 'A4-L',
                'destination' => 'D',
                'marginTop' => 20,
                'marginBottom' => 20,
                'cssInline' => '.kv-wrap{padding:20px;}' .
                    '.kv-align-center{text-align:center;}' .
                    '.kv-align-left{text-align:left;}' .
                    '.kv-align-right{text-align:right;}' .
                    '.kv-align-top{vertical-align:top!important;}' .
                    '.kv-align-bottom{vertical-align:bottom!important;}' .
                    '.kv-align-middle{vertical-align:middle!important;}' .
                    '.kv-page-summary{border-top:4px double #ddd;font-weight: bold;}' .
                    '.kv-table-footer{border-top:4px double #ddd;font-weight: bold;}' .
                    '.kv-table-caption{font-size:1.5em;padding:8px;border:1px solid #ddd;border-bottom:none;}',
                'methods' => [
                    'SetHeader' => [
                        ['odd' => $pdfHeader, 'even' => $pdfHeader]
                    ],
                    'SetFooter' => [
                        ['odd' => $pdfFooter, 'even' => $pdfFooter]
                    ],
                ],
                'options' => [
                    'title' => $title,
                    'subject' => Yii::t('kvgrid', 'PDF export generated by kartik-v/yii2-grid extension'),
                    'keywords' => Yii::t('kvgrid', 'krajee, grid, export, yii2-grid, pdf')
                ],
                'contentBefore'=>'',
                'contentAfter'=>''
            ]
        ],
        GridView::JSON => [
            'label' => Yii::t('kvgrid', 'JSON'),
            'icon' => $isFa ? 'file-code-o' : 'floppy-open',
            'iconOptions' => ['class' => 'text-warning'],
            'showHeader' => true,
            'showPageSummary' => true,
            'showFooter' => true,
            'showCaption' => true,
            'filename' => Yii::t('kvgrid', 'grid-export'),
            'alertMsg' => Yii::t('kvgrid', 'The JSON export file will be generated for download.'),
            'options' => ['title' => Yii::t('kvgrid', 'JavaScript Object Notation')],
            'mime' => 'application/json',
            'config' => [
                'colHeads' => [],
                'slugColHeads' => false,
                'jsonReplacer' => null,
                'indentSpace' => 4
            ]
        ],
    ];
    

    Note:

    You can choose to display only the download formats you want in the export menu and reorder them as you need. To hide a format, just do not add it to exportConfig. For example, to reorder the menu, to show CSV first, then HTML and PDF, and totally hide the rest, you could do this:

    'exportConfig' => [
        GridView::CSV => ['label' => 'Save as CSV'],
        GridView::HTML => [// html settings],
        GridView::PDF => [// pdf settings],
    ]
    
    You should note that, each format within the exportConfig needs to be set as an array.

Usage

use kartik\grid\GridView;

echo GridView::widget([
    'dataProvider'=> $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'toolbar'=>[
        '{export}',
        '{toggleData}'
    ]
]);

With release v2.2.0, the grid data can be toggled to show all (full) data if needed. You can configure a toggle button to be shown in the toolbar, that allows you to toggle between all data and paginated data. The following properties are available for the GridView object to configure your grid toggle data button:

  • toolbar: array, same as the settings for toolbar in the toolbar section. The special tag {toggleData} will be replaced with the toggle button.

  • toggleDataOptions: array, the settings for the toggle data button for the toggle data type. This will be setup as an associative array of $type => $options, where:

    • $type: string, is the type of data to display. Should be one of:

      • all: toggle button settings for all grid data display

      • page: toggle button for showing first page data

    • $options: array, is the HTML attributes for the button. The following special options are recognized:

      • icon: string, the glyphicon suffix name. If not set or empty will not be displayed.

      • label: string, the label for the button.

    The toggleDataOptions defaults to the following setting:

    [
        'all' => [
            'icon' => 'resize-full',
            'label' => Yii::t('kvgrid', 'All'),
            'class' => 'btn btn-default',
            'title' => 'Show all data'
        ],
        'page' => [
            'icon' => 'resize-small',
            'label' => Yii::t('kvgrid', 'Page'),
            'class' => 'btn btn-default',
            'title' => 'Show first page data'
        ],
    ]
    

Allows configuration of GridView to be enclosed in a panel that can be styled as per Bootstrap 3.x CSS markup. The panel will enable configuration of various sections to embed content/buttons, before and after header, and before and after footer.

  • panel: array, the panel settings. If this is set, the grid widget will be embedded in a Bootstrap panel. Applicable only if bootstrap is true. The following array keys are supported:

    • type: string, the Bootstrap contextual color type. Should be one of the GridView TYPE constants below. If not set will default to default or GridView::TYPE_DEFAULT.

      • GridView::TYPE_DEFAULT or 'default'

      • GridView::TYPE_PRIMARY or 'primary'

      • GridView::TYPE_INFO or 'info'

      • GridView::TYPE_DANGER or 'danger'

      • GridView::TYPE_WARNING or 'warning'

      • GridView::TYPE_SUCCESS or 'success'

    • heading: string|boolean, the panel heading. To hide and disable this section completely, set this to false.

    • headingOptions: array, HTML attributes for the heading container. Defaults to ['class'=>'panel-heading'].

    • footer: string|boolean, the panel footer. To hide and disable this section completely, set this to false.

    • footerOptions: array, HTML attributes for the footer container. Defaults to ['class'=>'panel-footer'].

    • before: string|boolean, the panel content to be placed before/above the grid table (after the panel heading). To hide and disable this section completely, set this to false.

    • beforeOptions: array, HTML attributes for the before container. Defaults to ['class'=>'kv-panel-before'].

    • after: string|boolean, the panel content to be placed after/above the grid table (before the panel footer). To hide and disable this section completely, set this to false.

    • afterOptions: array, HTML attributes for the after container. Defaults to ['class'=>'kv-panel-after'].

Usage

use kartik\grid\GridView;

// Create a panel layout for your GridView widget
echo GridView::widget([
    'dataProvider'=> $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'panel' => [
        'heading'=>'<h3 class="panel-title"><i class="glyphicon glyphicon-globe"></i> Countries</h3>',
        'type'=>'success',
        'before'=>Html::a('<i class="glyphicon glyphicon-plus"></i> Create Country', ['create'], ['class' => 'btn btn-success']),
        'after'=>Html::a('<i class="glyphicon glyphicon-repeat"></i> Reset Grid', ['index'], ['class' => 'btn btn-info']),
        'footer'=>false
    ],
]);

The grid layout templates have been enhanced for enclosing in the panel. You can create your own template by setting the following parameter:

  • layout: string, will be automatically set based on panel settings. If panel is a valid array, the layout will default to the panelTemplate property. If panel property is set to false, the layout defaults to {summary}\n{items}\n{pager}.

    Note

    You can use the following additional special variables in the grid layout property:
    • {export}: Will be replaced with the grid export button menu.

    • {toolbar}: Will be replaced with the toolbar property set.

  • panelTemplate: string, the template for rendering the entire panel layout. The following special variables are recognized and will be replaced:

    • {type}: The panel contextual type (one of the GridView TYPE constants).

    • {panelHeading}: The panel heading block which will be rendered using panelHeadingTemplate.

    • {panelBefore}: The content to be placed before the grid header and after the panel heading. This will be rendered using panelBeforeTemplate.

    • {panelAfter}: The content to be placed after the grid footer and before the panel footer. This will be rendered using panelAfterTemplate.

    • {panelFooter}: The panel footer block which will be rendered using panelFooterTemplate.

    • {summary}: Will be replaced with the GridView summary information.

    • {items}: The grid table content.

    • {sort}: The grid sort content.

    • {pager}: The grid pager content.

    The panelTemplate defaults to:

    <div class="panel {type}">
        {panelHeading}
        {panelBefore}
        {items}
        {panelAfter}
        {panelFooter}
    </div>
    
  • panelHeadingTemplate: string, the template for rendering the panel heading block. The following special variables are recognized and will be replaced:

    • {heading}: The heading text/content which will be passed via panel['heading'] setting.

    • {summary}: Will be replaced with the GridView summary information.

    • {items}: The grid table content.

    • {sort}: The grid sort content.

    • {pager}: The grid pager content.

    • {export}: Will be replaced with the grid export button menu.

    • {toolbar}: Will be replaced with the toolbar property set.

    The panelHeadingTemplate defaults to:

    <div class="pull-right">
        {summary}
    </div>
    <h3 class="panel-title">
        {heading}
    </h3>
    <div class="clearfix"></div>
    
  • panelBeforeTemplate: string, the template for rendering the panel before block. The following special variables are recognized and will be replaced:

    • {before}: The before text/content which will be passed via panel['before'] setting.

    • {summary}: Will be replaced with the GridView summary information.

    • {items}: The grid table content.

    • {sort}: The grid sort content.

    • {pager}: The grid pager content.

    • {export}: Will be replaced with the grid export button menu.

    • {toolbar}: Will be replaced with the toolbar property set.

    The panelBeforeTemplate defaults to:

    <div class="pull-right">
        <div class="btn-toolbar kv-grid-toolbar" role="toolbar">
            {toolbar}
        </div>    
    </div>
    {before}
    <div class="clearfix"></div>
    
  • panelAfterTemplate: string, the template for rendering the panel after block. The following special variables are recognized and will be replaced:

    • {after}: The after text/content which will be passed via panel['after'] setting.

    • {summary}: Will be replaced with the GridView summary information.

    • {items}: The grid table content.

    • {sort}: The grid sort content.

    • {pager}: The grid pager content.

    • {export}: Will be replaced with the grid export button menu.

    • {toolbar}: Will be replaced with the toolbar property set.

    The panelAfterTemplate defaults to:

    {after}
    
  • panelFooterTemplate: string, the template for rendering the panel footer block. The following special variables are recognized and will be replaced:

    • {footer}: The footer text/content which will be passed via panel['footer'] setting.

    • {summary}: Will be replaced with the GridView summary information.

    • {items}: The grid table content.

    • {sort}: The grid sort content.

    • {pager}: The grid pager content.

    • {export}: Will be replaced with the grid export button menu.

    • {toolbar}: Will be replaced with the toolbar property set.

    The panelFooterTemplate defaults to:

    <div class="kv-panel-pager">
        {pager}
    </div>
    {footer}
    <div class="clearfix"></div>
    

The grid offers ability to plugin components or widgets. The export property has been enhanced to add additional items for export if needed through external code. In addition, one can virtually define their own tags in the grid layout - and dynamically replace them via code at runtime. This is achievable by setting the following property for the grid:

  • replaceTags: array, tags to replace in the rendered layout. Enter this as an associative array of the format $key => $value, where:

    • $key: string, is the tag you wish to replace. You can define any tag and use it in your layout template.

    • $value: string|Closure, the value that will be replaced. If set as a string, it will be directly replaced. You can also set it as a callback function that will return a string. The function should be of the signature:function ($widget) { return 'custom'; }

    For example:
    ['{flag}' => '<span class="glyphicon glyphicon-asterisk"></span']
    

Usage

use kartik\grid\GridView;
use yii\helpers\Html;

// shows how you can add in your own tags e.g. {custom}
$layout = <<< HTML
<div class="pull-right">
    {summary}
</div>
{custom}
<div class="clearfix"></div>
{items}
{pager}
HTML;

// Plugin components using `replaceTags`
echo GridView::widget([
    'dataProvider'=> $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'layout' => $layout,
    'replaceTags' => [
        '{custom}' => function($widget) {
            // you could call other widgets/custom code here
            if ($widget->panel === false) {
                return '';
            } else {
                return '';
            }
        }
    ]
]);

Click here to watch various demonstration examples of grid grouping.

With release v3.0.5, the module allows grouping of GridView data by setting various group related properties at the kartik\grid\DataColumn level. The following functionalities are supported:

  • Ability to group and merge similar data for each column.

  • Allow multi level/complex grouping and making a sub group dependent on a parent group.

  • Allow displaying grouped data as a separate grouped row above the child rows.

  • Allow configuring and displaying of group level summary rows.

  • Summaries can be setup as a group footer OR a group header.

  • Summaries intelligently embed between sub-groups and parent groups.

  • Summaries can include auto calculated values (for numbers) at runtime based on previous child column data.

  • Summaries can include advanced calculations using a javascript callback configuration.

  • Ability to merge columns in the summary group header or footer.

  • Complex configurations of groups will allow - group properties to be set dynamically using Closure.

  • Allow you to style your group cells in various ways including setting odd and even row CSS properties.

Important

For grid grouping to work effectively, all your grid column classes MUST be based on grid column classes from the yii2-grid extension.

You can set the following properties for each DataColumn for configuring the group grid. The grid grouping properties are available within \kartik\grid\DataColumn.

  • group: boolean, whether to enable grouping for the grid column. Defaults to false. When enabled, the widget will automatically attempt to group similar sequential row data into one single column. You must setup your data provider query to sort default by this column, for the column grouping to be effective.

  • groupedRow: boolean|Closure, whether to add a separate group row for grouping. This is validated only if group is set to true. Defaults to false. If set to true, the column will be hidden and its value will be displayed in a separate row above. The default behavior is to show the grouped content in a separate column (when this property is false). If setup as a Closure, the signature of the function should be: function ($model, $key, $index, $column), where $model, $key, and $index refer to the model, key and index of the row currently being rendered, and $column is a reference to the \kartik\grid\DataColumn object.

  • groupOddCssClass: string|Closure, the odd group css class. Defaults to kv-group-odd. This is validated only if group is set to true. If setup as a Closure, the signature of the function should be: function ($model, $key, $index, $column), where $model, $key, and $index refer to the model, key and index of the row currently being rendered, and $column is a reference to the \kartik\grid\DataColumn object.

  • groupEvenCssClass: string|Closure, the even group css class. Defaults to kv-group-even. This is validated only if group is set to true. If setup as a Closure, the signature of the function should be: function ($model, $key, $index, $column), where $model, $key, and $index refer to the model, key and index of the row currently being rendered, and $column is a reference to the \kartik\grid\DataColumn object.

  • subGroupOf: integer|Closure, the column index number (starting from 0 for the left-most column) for which this group is a sub group of. This is validated only if group is set to true. The grid will automatically reset and style sub groups within parent groups based on this setting. If setup as a Closure, the signature of the function should be: function ($model, $key, $index, $column), where $model, $key, and $index refer to the model, key and index of the row currently being rendered, and $column is a reference to the \kartik\grid\DataColumn object.

  • groupHeader: array|Closure, the configuration of the group header which will be displayed as a separate row above the group. If this is empty, no group header will be rendered. This is validated only if group is set to true. If setup as a Closure, the signature of the function should be: function ($model, $key, $index, $column), where $model, $key, and $index refer to the model, key and index of the row currently being rendered, and $column is a reference to the \kartik\grid\DataColumn object. The following array keys are recognized:

    • mergeColumns: array, the columns that will be merged as from, to pairs. For example if you need to merge in the summary row, the column numbers 0 to 2 and column numbers 3 to 6, you can set this as:

      [
          [0, 2], 
          [3, 6]
      ]
      
    • content: array, header content for each column. You must set this as $key => $value pair, where $key is the 0 based index for the column, and $value is the content to display for the column. The $value can take in special function names to summarize values for the column. If set to one of GridView::F_COUNT, GridView::F_SUM, GridView::F_AVG, GridView::F_MAX, or GridView::F_MIN, the values will be auto summarized.

    • contentFormats: array, header content formats for each column. This is only applicable currently only for a number type value in the summary or when you are calling your own custom formatting routine, using a javascript callback. You must set this as $key => $value pair, where $key is the 0 based index for the column, and $value is the format settings for the column. The $value a format specification setup as an array containing one or more of the following options:

      • format: string, whether number or callback

      • decimals: integer, number of decimals (for number format only). Defaults to 0.

      • decPoint: string, decimals point character (for number format only). Defaults to ..

      • thousandSep: string, thousands separator character (for number format only). Defaults to ,.

      • func: string, the javascript callback function name (for callback format only). This should be set to a globally accessible javascript function name. For example if you set this to `customCallback`, the function should be of the signature: `function customCallback(source, data) { return custom_convert(source, data); }`. The parameters for the callback function that will be passed and available are:

        • source: string, the summary column source as set in `content` section if available

        • data: array, the text values of each of the child columns in this group.

        An example of configuring the contentFormats could be:

        [
            7 => ['format'=>'callback', 'func'=>new yii\web\JsExpression('customCallback')]
            8 => ['format'=>'number', 'decimals'=>2, 'decPoint'=>'.', 'thousandSep'=>',']
        ]
        
    • contentOptions: array, configuration of HTML attributes for each header summary column cell. You must set this as $key => $value pair, where $key is the 0 based index for the column, and $value is the array of HTML attributes for the column. For example:

      [
          0 => ['style'=>'font-weight:bold'],
          8 => ['style'=>'text-align:right']
      ]
      
    • options: array, HTML attributes for the group header row.

  • groupFooter: array|Closure, the configuration of the group footer which will be displayed as a separate row below the group. If this is empty, no group footer will be rendered. This is validated only if group is set to true. If setup as a Closure, the signature of the function should be: function ($model, $key, $index, $column), where $model, $key, and $index refer to the model, key and index of the row currently being rendered, and $column is a reference to the \kartik\grid\DataColumn object. The following array keys are recognized:

    • mergeColumns: array, the columns that will be merged as from, to pairs. For example if you need to merge in the summary row, the column numbers 0 to 2 and column numbers 3 to 6, you can set this as:

      [
          [0, 2], 
          [3, 6]
      ]
      
    • content: array, footer content for each column. You must set this as $key => $value pair, where $key is the 0 based index for the column, and $value is the content to display for the column. The $value can take in special function names to summarize values for the column. If set to one of GridView::F_COUNT, GridView::F_SUM, GridView::F_AVG, GridView::F_MAX, or GridView::F_MIN, the values will be auto summarized.

    • contentFormats: array, footer content formats for each column. This is only applicable currently only for a number type value in the summary or when you are calling your own custom formatting routine, using a javascript callback. You must set this as $key => $value pair, where $key is the 0 based index for the column, and $value is the format settings for the column. The $value a format specification setup as an array containing one or more of the following options:

      • format: string, whether number or callback

      • decimals: integer, number of decimals (for number format only). Defaults to 0.

      • decPoint: string, decimals point character (for number format only). Defaults to ..

      • thousandSep: string, thousands separator character (for number format only). Defaults to ,.

      • func: \yii\web\JsExpression, the javascript callback function (for callback format only). This must be setup as a javascript function of the signature: function (source) { return custom_convert(source, data); }. The module allows the following parameters for access to the callback function:

        • source: string, the summary column source as set in `content` section if available

        • data: array, the text values of each of the child columns in this group.

        An example of configuring the contentFormats could be:

        [
            7 => ['format'=>'callback', 'func'=>new yii\web\JsExpression('customCallback')]
            8 => ['format'=>'number', 'decimals'=>2, 'decPoint'=>'.', 'thousandSep'=>',']
        ]
        
    • contentOptions: array, configuration of HTML attributes for each footer summary column cell. You must set this as $key => $value pair, where $key is the 0 based index for the column, and $value is the array of HTML attributes for the column. For example:

      [
          0 => ['style'=>'font-weight:bold'],
          8 => ['style'=>'text-align:right']
      ]
      
    • options: array, HTML attributes for the group footer row.

Note that other DataColumn properties can be used along with the above in combination as well. For example DataColumn::contentOptions can help style each group cell.

Click here to watch various demonstration examples of grid grouping.

Click here to watch various demonstration examples of excel export formatting.

With release v3.0.6, the grid allows you to configure formats of data exported in EXCEL format. The following properties are available to control this:

The following properties are available within \kartik\grid\GridView to control your Excel Export formats:

  • autoXlFormat: boolean, applicable for EXCEL export content only. This determines whether the exported EXCEL cell data will be automatically guessed and formatted based on DataColumn::format property. You can override this behavior and change the auto-derived format mask by setting DataColumn::xlFormat for each column. It is important that you must set the DataColumn::format property for this to work effectively.

The following properties are available within \kartik\grid\DataColumn, \kartik\grid\FormulaColumn, \kartik\grid\EditableColumn, \kartik\grid\BooleanColumn, and \kartik\grid\SerialColumn to control your Excel Export formats:

  • xlFormat: string, the cell format for EXCEL exported content. This will override any auto set format due to GridView::autoXlFormat. Note that excel cell formats needs to be set using mso-number-format specifications. It is important that you must set the format property for this to work effectively.

  • format: string|array, in which format should the value of each data model be displayed as (e.g. "raw", "text", "html", ['date', 'php:Y-m-d']). Supported formats are determined by the GridView::formatter|formatter used by the GridView. Default format is "text" which will format the value as an HTML-encoded plain text when \yii\i18n\Formatter is used as the GridView::$formatter|formatter of the GridView.

Click here to watch various demonstration examples of excel export formatting.

The default Yii data column has been enhanced with various additional parameters.

Note

The DataColumn supports various grid grouping properties. Refer the Grid Grouping section for details.
  • format: string|array, in which format should the value of each data model be displayed as (e.g. "raw", "text", "html", ['date', 'php:Y-m-d']). Supported formats are determined by the GridView::formatter|formatter used by the GridView. Default format is "text" which will format the value as an HTML-encoded plain text when \yii\i18n\Formatter is used as the GridView::$formatter|formatter of the GridView.

  • xlFormat: string, the cell format for EXCEL exported content. This will override any auto set format due to GridView::autoXlFormat. Note that excel cell formats needs to be set using mso-number-format specifications. It is important that you must set the format property for this to work effectively. Refer the Excel Export Formatting section for details.

  • hidden: boolean whether the column is hidden from display. This is different than the visible property, in the sense, that if this is true the column is rendered, but hidden from display. This will allow you to still export the column using the export function.

  • hiddenFromExport: boolean whether the entire column is hidden from export but shown on display (the opposite of hidden). Defaults to false.

  • hAlign: string the horizontal alignment of the column. This will automatically set the header, body, footer, and page summary to this alignment. Should be one of GridView ALIGN constants as mentioned below.

    • GridView::ALIGN_RIGHT or 'right'

    • GridView::ALIGN_CENTER or 'center'

    • GridView::ALIGN_LEFT or 'left'

  • vAlign: string the vertical alignment of the column. This will automatically set the header, body, footer, and page summary to this alignment. Should be one of GridView ALIGN constants as mentioned below.

    • GridView::ALIGN_TOP or 'top'

    • GridView::ALIGN_MIDDLE or 'middle'

    • GridView::ALIGN_BOTTOM or 'bottom'

  • noWrap: boolean whether to force no wrapping on all table cells for the column. This will automatically set the header, body, footer, and page summary to not wrap using the white-space wrap CSS style. Defaults to false.

  • width: string the width of each column - matches the CSS width property. This will automatically set the header, body, footer, and page summary to this value.

  • filterType: string the filter input type for each column. This allows you to set a filter input type other than the default text or dropdown list. You can pass in any widget classname extending from the Yii Input Widget. In most cases, you can use one of predefined kartik\widgets from the GridView FILTER constants as mentioned below:

    • Input widgets by Krajee:

      • GridView::FILTER_SELECT2 or '\kartik\widgets\Select2'

      • GridView::FILTER_TYPEAHEAD or '\kartik\widgets\Typeahead'

      • GridView::FILTER_SWITCH or '\kartik\widgets\Switch'

      • GridView::FILTER_SPIN or '\kartik\widgets\TouchSpin'

      • GridView::FILTER_STAR or '\kartik\widgets\StarRating'

      • GridView::FILTER_DATE or '\kartik\widgets\DatePicker'

      • GridView::FILTER_TIME or '\kartik\widgets\TimePicker'

      • GridView::FILTER_DATETIME or '\kartik\widgets\DateTimePicker'

      • GridView::FILTER_DATE_RANGE or '\kartik\widgets\DateRangePicker'

      • GridView::FILTER_RANGE or '\kartik\widgets\RangeInput'

      • GridView::FILTER_COLOR or '\kartik\widgets\ColorInput'

      • GridView::FILTER_SLIDER or '\kartik\slider\Slider'

      • GridView::FILTER_MONEY or '\kartik\money\MaskMoney'

    • Other input types

      • GridView::FILTER_CHECKBOX or 'checkbox'

      • GridView::FILTER_RADIO or 'radio'

    IMPORTANT:

    Do not use GridView::FILTER_TIME as a filter currently, because of a bug in bootstrap-timepicker plugin. This is also a recorded issue, and will depend on the fix in the source plugin.
  • filterWidgetOptions: array the options/settings for the filter widget. Will be used only if you set filterType to a widget classname that exists.

  • mergeHeader: boolean whether to merge the header title row and the filter row. This is useful when you do not have a filter applicable for the column (e.g.the ActionColumn or the SerialColumn). This will not render the filter for the column and can be used when filter is set to false. Defaults to false.

    NOTE:

    The header merging will be done, only when filterPosition property for the grid is set to GridView::FILTER_POS_BODY.
  • pageSummary: boolean|string | Closure the page summary that is displayed above the footer. You can set it to one of the following:

    • false: the summary will not be displayed.

    • true: the page summary for the column will be calculated and displayed using the pageSummaryFunc setting.

    • any string: will be displayed as is

    • Closure: you can set it to an anonymous function with the following signature:

    // example 1
    function ($summary, $data, $widget) { return 'Count is ' . $summary; }
    
    // example 2
    function ($summary, $data, $widget) { return 'Range ' . min($data) . ' to ' . max($data); }
    

    where

    • the $summary variable will be replaced with the calculated summary using the summaryFunc setting.

    • the $data variable will contain array of the selected page rows for the column.

  • pageSummaryFunc: string the summary function used to calculate the page summary for the column. Defaults to GridView::F_SUM. Should be one of the following GridView F constants.

    • GridView::F_COUNT or 'f_count'

    • GridView::F_SUM or 'f_sum'

    • GridView::F_MAX or 'f_max'

    • GridView::F_MIN or 'f_min'

    • GridView::F_AVG or 'f_avg'

  • pageSummaryOptions: array HTML attributes for the page summary cell. The following additional special attributes are recognized:

    • prepend: string a prefix string that will be prepended before the pageSummary content

    • append: string a suffix string that will be appended after the pageSummary content

  • hidePageSummary: boolean whether to just hide the page summary for display but still calculate the summary based on pageSummary settings.

'columns' => [
    [
        'class' => '\kartik\grid\DataColumn',
        'attribute' => 'amount',
        'pageSummary' => true
    ]
]

This is a new grid column class that extends the \kartik\grid\DataColumn class and allows one to expand grid rows, show details, or load content via ajax. The features available with this column are:

  1. Ability to expand grid rows and show a detail content in a new row below it like a master-detail record.

  2. By default shows a toggle icon to expand/collapse each row or toggle all rows. You can also change this behavior to ENABLE toggling by ENTIRE ROW CLICK, by setting enableRowClick to true.

  3. Allows configuring the column like any grid DataColumn. The value of the column determines if the row is to be expanded or collapsed by default.

  4. Allows you to configure / customize the expand and collapse indicators.

  5. Ability to configure only specific rows to have expand/collapse functionality.

  6. Ability to disable the expand / collapse behavior and indicators for selective rows.

  7. Allows you to configure the detail content markup directly in the column configuration (using `detail` property). This can be set as a HTML markup directly or via Closure callback using column parameters.

  8. Allows you to load the detail content markup via ajax. Set the `detailUrl` property directly or via a Closure callback using column parameters.

  9. Automatically caches the content loaded via ajax so that the content is rendered from local on toggling the expand / collapse indicators, until the grid state is changed via filtering, sorting, or pagination.

  10. Ability to batch expand or batch collapse grid rows from the header. If content is loaded via ajax, the batch expand and collapse will fire the ajax requests to load and use intelligently from cache where possible.

  11. Triggers jQuery events on the grid element for advanced processing.

The ExpandRowColumn includes these configuration settings:

  • value: string | Closure the value of this attribute (should return an integer) that will identify the state of the current row. This should be normally setup as a Closure callback. For example:

    function ($model, $key, $index) { 
        return GridView::ROW_EXPANDED;
    }
    

    If you are setting this as a string, then it will be evaluated as the attribute name in the model for which the value will be parsed. The following return states are supported as a value for this column:

    • GridView::ROW_EXPANDED or 0: the row will be expanded by default and will display the collapse indicator.

    • GridView::ROW_COLLAPSED or 1: the row will be collapsed by default and will display the expand indicator.

    • GridView::ROW_NONE or -1: no indicator will be displayed for the row.

    If this is not set, $model[$attribute] will be used to obtain the value. If this value is evaluated as empty or null, it is treated as GridView::ROW_NONE. This can also be an anonymous function (Closure) that returns one of the values above. The anonymous function should have the signature function ($model, $key, $index, $column), where:

    • model mixed is the data model

    • key mixed is the key associated with the data model

    • index integer is the zero-based index of the data model among the models array returned by GridView::dataProvider

    • column ExpandRowColumn is the column object instance

  • enableRowClick: boolean whether to toggle the expansion/collapse by clicking on the table row. Defaults to false. To disable row click for specific elements within the row you can add the CSS class kv-disable-click to tags/elements to disable the toggle functionality.

  • rowClickExcludedTags: array list of tags in the row on which row click will be skipped when enableRowClick is true. Defaults to ['a', 'button', 'input'].

  • extraData: array additional data that will be passed to the ajax load function as key value pairs.

  • expandIcon: string icon for the expand indicator. If this is not set, it will derive values automatically using the following rules:

    • If GridView bootstrap property is set to true, it will default to GridView::ICON_EXPAND or <span class="glyphicon glyphicon-expand"></span>

    • If GridView bootstrap property is set to false, then it will default to +

  • collapseIcon: string icon for the collapse indicator. If this is not set, it will derive values automatically using the following rules:

    • If GridView bootstrap property is set to true, it will default to GridView::ICON_EXPAND or <span class="glyphicon glyphicon-collapse-down"></span>

    • If GridView bootstrap property is set to false, then it will default to -

  • expandTitle: string title to display on hover of expand indicator for each row. Defaults to Expand. This will automatically translate for the application language using the extension's translation message configuration files.

  • collapseTitle: string title to display on hover of collapse indicator for each row. Defaults to Collapse. This will automatically translate for the application language using the extension's translation message configuration files.

  • expandAllTitle: string title to display of expand indicator at the header. Defaults to Expand All. This will automatically translate for the application language using the extension's translation message configuration files.

  • collapseAllTitle: string title to display on hover of collapse indicator at the header. Defaults to Collapse All. This will automatically translate for the application language using the extension's translation message configuration files.

  • expandOneOnly: boolean nly one row to be expanded at a time and auto collapse other expanded rows whenever a row is expanded. Defaults to false.

  • allowBatchToggle: boolean allow batch expansion or batch collapse of all rows by clicking the header indicator. Defaults to true.

  • defaultHeaderState: int default state of the header. The following states are supported:

    • GridView::ROW_EXPANDED or 0: Will set all rows to expanded and will display the collapseIcon indicator.

    • GridView::ROW_COLLAPSED or 1: Will set all rows to collapsed and will display the expandIcon indicator.

  • enableCache: boolean whether to enable caching of ajax loaded content for the session after first use. Defaults to true.

  • disabled: boolean | Closure whether the expand icon indicator is disabled. Defaults to false. If set to true, the indicator is disabled, and one cannot collapse or expand the sections.This can also be an anonymous function (Closure) having the signature function ($model, $key, $index, $column), where:

    • model mixed is the data model

    • key mixed is the key associated with the data model

    • index integer is the zero-based index of the data model among the models array returned by GridView::dataProvider

    • column ExpandRowColumn is the column object instance

  • detail: string | Closure the detail content (html markup) to be displayed in the expanded row. Either detail OR detailUrl must be entered. This can be a normal html markup or an anonymous function that returns the markup. This can also be an anonymous function (Closure). The anonymous function should have the signature function ($model, $key, $index, $column), where:

    • model mixed is the data model

    • key mixed is the key associated with the data model

    • index integer is the zero-based index of the data model among the models array returned by GridView::dataProvider

    • column ExpandRowColumn is the column object instance

  • detailUrl: string the url/action that would render the detail content via ajax. Either detail OR detailUrl must be entered. The ajax response must return the content/markup to render. The extension automatically passes the following data parameters to the server URL as POST data:

    • expandRowKey mixed is the key associated with the data model

    • expandRowIndex integer is the zero-based index of the data model among the models array returned by GridView::dataProvider

    An example of a detailUrl response returning content is shown below:

    /**
     * Url action - /book/book-detail
     */
    public function actionBookDetail() {
        if (isset($_POST['expandRowKey'])) {
            $model = \app\models\Book::findOne($_POST['expandRowKey']);
            return $this->renderPartial('_book-details', ['model'=>$model]);
        } else {
            return '<div class="alert alert-danger">No data found</div>';
        }
    }
    
  • onDetailLoaded: string | JsExpression the javascript callback to execute after loading the content via ajax. Only applicable when detailUrl is provided.

  • detailOptions: array | Closure the HTML attributes for the expanded table row. This can be an array or an anonymous function of the signature: function ($model, $key, $index, $column), where:

    • model mixed is the data model

    • key mixed is the key associated with the data model

    • index integer is the zero-based index of the data model among the models array returned by GridView::dataProvider

    • column ExpandRowColumn is the column object instance

  • detailRowCssClass: string the CSS class for the detail content table row. Defaults to GridView::TYPE_INFO.

  • detailAnimationDuration: string | integer the jQuery sliding animation duration to slide up/down the detail row. Defaults to slow

The following parameters are similar to the DataColumn settings. Default values for these parameters have been carefully set for usage in most scenarios, thus accelerating development.

  • hAlign: string, defaults to GridView::ALIGN_CENTER

  • width: string, defaults to 50px

  • pageSummary: boolean, defaults to false

  • hiddenFromExport: boolean, defaults to true

  • mergeHeader: boolean, defaults to true

The following jQuery plugin events are available for the expand row column. Each of these events are triggered on the grid element identified by grid's options[id].

  • kvexprow.toggle: This event is triggered on toggling an expand column in each table row and will trigger for either expand or collapse. The event sends the following parameters for advanced parsing:

    • ind: int, the row index

    • key: mixed, the row key

    • extra: object, the extra data object set as key value pairs via the ExpandRowColumn extraData property

    • state: boolean, whether expanded true or collapsed false.

    var $grid = $('#grid-id');
    $grid.on('kvexprow.toggle', function (event, ind, key, extra, state) {
        console.log('Toggled expand row');
    });
    
  • kvexprow.toggleAll: This event is triggered on toggling all rows by clicking the toggle indicator on the table header. The event sends the following parameters for advanced parsing:

    • extra: object, the extra data object set as key value pairs via the ExpandRowColumn extraData property

    • state: boolean, whether expanded true or collapsed false.

    var $grid = $('#grid-id');
    $grid.on('kvexprow.toggleAll', function (event, extra, state) {
        console.log('Toggled all rows');
    });
    
  • kvexprow.beforeLoad: This event is triggered before the call to ajax load. This occurs when you set the detailUrl property in ExpandRowColumn for triggering the ajax call to load expanded content.

    • ind: int, the row index

    • key: mixed, the row key

    • extra: object, the extra data object set as key value pairs via the ExpandRowColumn extraData property

    var $grid = $('#grid-id');
    $grid.on('kvexprow.beforeLoad', function (event, ind, key, extra) {
        console.log('Before ajax load.');
    });
    
  • kvexprow.loaded: This event is triggered after the ajax content has been successfully loaded. This occurs when you set the detailUrl property in ExpandRowColumn for triggering the ajax call to load expanded content.

    • ind: int, the row index

    • key: mixed, the row key

    • extra: object, the extra data object set as key value pairs via the ExpandRowColumn extraData property

    var $grid = $('#grid-id');
    $grid.on('kvexprow.loaded', function (event, ind, key, extra) {
        console.log('After ajax load completed.');
    });
    

Important

To ensure each record in your data is updated correctly even if they are rearranged correctly from the POST submission you should setup your dataProvider query to use indexBy method to index your records by primary key. For example:

$query = Model::find()->indexBy('id'); // where `id` is your primary key

$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);

View this complete web tip on how to setup your model, controller, and view with GridView Editable columns to manipulate records.

This is a new grid column class that extends the \kartik\grid\DataColumn class. It allows you to make the grid content directly editable by clicking it. You can selectively choose to disable editable for certain rows or all rows. This column uses the enhanced kartik\editable\Editable widget to make the grid content editable. You can set the following properties for the column:
  • format: string|array, in which format should the value of each data model be displayed as (e.g. "raw", "text", "html", ['date', 'php:Y-m-d']). Supported formats are determined by the GridView::formatter|formatter used by the GridView. Default format is "text" which will format the value as an HTML-encoded plain text when \yii\i18n\Formatter is used as the GridView::$formatter|formatter of the GridView.

  • xlFormat: string, the cell format for EXCEL exported content. This will override any auto set format due to GridView::autoXlFormat. Note that excel cell formats needs to be set using mso-number-format specifications. It is important that you must set the format property for this to work effectively. Refer the Excel Export Formatting section for details.

  • hidden: boolean whether the column is hidden from display. This is different than the visible property, in the sense, that if this is true the column is rendered, but hidden from display. This will allow you to still export the column using the export function.

  • hiddenFromExport: boolean whether the entire column is hidden from export but shown on display (the opposite of hidden). Defaults to false.

  • editableOptions: array | Closure the configuration options for the kartik\editable\Editable widget. The model and attribute properties will automatically be derived from the grid column setting. Refer the Editable documentation for all supported options. If not set as an array, this can be passed as a callback function of the signature: function ($model, $key, $index), where:

    • model: mixed is the data model.

    • key: mixed is the key associated with the data model.

    • index: integer is the zero-based index of the data model among the models array returned by GridView::dataProvider.

    • widget: EditableColumn is the current editable column widget instance.

    An example of setting editableOptions as a callback function is shown below

    'editableOptions'=> function ($model, $key, $index) {
        return [
            'header'=>'Name', 
            'size'=>'md',
            'beforeInput' => function ($form, $widget) use ($model, $index) {
                echo $form->field($model, "publish_date")->widget(\kartik\widgets\DatePicker::classname(), [
                    'options' => ['id' => "publish_date_{$index}"]
                ]);
            }
            'afterInput' => function ($form, $widget) use ($model, $index) {
                echo $form->field($model, "[{$index}]color")->widget(\kartik\widgets\ColorInput::classname(), [
                     'options' => ['id' => "publish_date_{$index}"]
                ]);
            }
        ];
    }
    
  • readonly: boolean whether the column is hidden from display. This is different than the visible property, in the sense, that if this is true the column is rendered, but hidden from display. This will allow you to still export the column using the export function.

  • refreshGrid: boolean whether to refresh the grid on successful submission of editable form. Defaults to false.

    Important

    When you set refreshGrid to true, it will trigger the refresh of your grid after you have submitted/saved the editable input. This will be a user-friendly ajax based refresh when you have pjax enabled for your grid. Setting this to true is useful, when you have for example page summary enabled for the column. The summary can be refreshed after every editable update.
  • readonly: boolean whether to prevent rendering the editable behavior and display a readonly data. You can also set this up as an anonymous function of the form function($model, $key, $index, $widget) that will return a boolean value, where:.

    options. If not set as an array, this can be passed as a callback function of the signature: function ($model, $key, $index), where:

    • model: mixed is the data model.

    • key: mixed is the key associated with the data model.

    • index: integer is the zero-based index of the data model among the models array returned by GridView::dataProvider.

    • widget: EditableColumn is the current editable column widget instance.

Processing Editable Data

In addition to the editable input value that will be returned via form POST action, the Editable Column automatically stores the following hidden inputs, for retrieval via your controller action:
  • editableIndex the grid row index to which the editable data belongs.

  • editableKey the grid primary key to which the editable data belongs. If the grid's data has a primary key which is numeric or string, then it would be returned as is. However, if the grid data has a composite primary key (array) or an object as a key (as used in mongo db), then this will return a PHP serialized string, that can be parsed using the PHP unserialize method.

The EditableColumnAction offers a quick easy way to setup your controller action for updating, saving and managing the EditableColumn output from GridView. This action class extends from yii\rest\Action and hence all properties available with yii\rest\Action are applicable here. The basic setup of the column involves setting up the controller action and the EditableColumn.

For a better understanding, view this complete web tip for setting up an EditableColumnAction for easily managing Editable content in GridView.
use kartik\grid\EditableColumnAction;
use yii\web\Controller;
use yii\helpers\ArrayHelper;
use app\models\Book;

class SiteController extends Controller
{
   public function actions()
   {
       return ArrayHelper::merge(parent::actions(), [
           'editbook' => [                                       // identifier for your editable column action
               'class' => EditableColumnAction::className(),     // action class name
               'modelClass' => Book::className(),                // the model for the record being edited
               'outputValue' => function ($model, $attribute, $key, $index) {
                     return (int) $model->$attribute / 100;      // return any custom output value if desired
               },
               'outputMessage' => function($model, $attribute, $key, $index) {
                     return '';                                  // any custom error to return after model save
               },
               'showModelErrors' => true,                        // show model validation errors after save
               'errorOptions' => ['header' => '']                // error summary HTML options
               // 'postOnly' => true,
               // 'ajaxOnly' => true,
               // 'findModel' => function($id, $action) {},
               // 'checkAccess' => function($action, $model) {}
           ]
       ]);
   }
}

In your GridView editable column configuration, include the above controller action for processing the Editable within editableOptions. For example

'editableOptions'=> ['formOptions' => ['action' => ['/site/editbook']]]
For a better understanding, view this complete web tip for setting up an EditableColumnAction for easily managing Editable content in GridView.

The following properties are available for configuration in \kartik\grid\EditableColumnAction.

  • outputValue: string|Closure, the output value from the editable. Defaults to empty string. If set as a string, it will be returned as is. If set as a callback (Closure), the signature of the callback would be function ($model, $attribute, $key, $index) { }, where:

    • model: Model, is the data model.

    • attribute: string, the attribute name for which the editable plugin is initialized.

    • key: mixed, is the key associated with the data model.

    • index: int, is the is the row index for the EditableColumn cell.

  • outputMessage: string|Closure, the output error message from the editable. Defaults to empty string. If set as a string, it will be returned as is. If set as a callback (Closure), the signature of the callback would be function ($model, $attribute, $key, $index) { }, where:

    • model: Model, is the data model.

    • attribute: string, the attribute name for which the editable plugin is initialized.

    • key: mixed, is the key associated with the data model.

    • index: int, is the row index for the EditableColumn cell.

  • showModelErrors: bool, whether to show model errors if outputMessage is empty or not set. Defaults to true

  • errorOptions: array, the options for error summary as supported by options param in yii\helpers\Html::errorSummary(). Defaults to ['header' => ''].

  • postOnly: bool, whether to allow access to this action for POST requests only. Defaults to true.

  • ajaxOnly: bool, whether to allow access to this action for AJAX requests only. Defaults to true.

Note

The FormulaColumn supports various grid grouping properties. Refer the Grid Grouping section for details.

This is a new grid column class that extends the \kartik\grid\DataColumn class. It allows calculated data for the column, based on values of other columns in the grid (just like spreadsheets). The formula calculation is done at grid rendering runtime and does not need to query the database. Hence you can use formula columns to calculate data from any DataColumn including calculated data from other FormulaColumn (except self-referencing itself). You would need to set the following parameters for setting up this column:

  • format: string|array, in which format should the value of each data model be displayed as (e.g. "raw", "text", "html", ['date', 'php:Y-m-d']). Supported formats are determined by the GridView::formatter|formatter used by the GridView. Default format is "text" which will format the value as an HTML-encoded plain text when \yii\i18n\Formatter is used as the GridView::$formatter|formatter of the GridView. Note that this is a property available only in kartik\grid\SerialColumn and not the yii\grid\DataColumn.

  • xlFormat: string, the cell format for EXCEL exported content. This will override any auto set format due to GridView::autoXlFormat. Note that excel cell formats needs to be set using mso-number-format specifications. It is important that you must set the format property for this to work effectively. Refer the Excel Export Formatting section for details.

  • autoFooter: boolean automatically generate the footer. If set to true, it will use the same formula to generate the footer. If set to false, will use the default footer.

  • hidden: boolean whether the column is hidden from display. This is different than the visible property, in the sense, that if this is true the column is rendered, but hidden from display. This will allow you to still export the column using the export function.

  • hiddenFromExport: boolean whether the entire column is hidden from export but shown on display (the opposite of hidden). Defaults to false.

  • value: Closure this must be passed as a Closure anonymous function having the signature function ($model, $key, $index, $widget) { }, where,

    • $model: mixed, the current data model being rendered

    • $key: mixed,the key associated with the data model

    • $index: integer, the zero-based index of the data model in the model array returned by dataProvider

    • $widget: DataColumn, the DataColumn or FormulaColumn object instance

    You can use the col($i, $params) function to refer a column value in every row. The $i is the column based index (starting from 0 from the leftmost column of the grid). The $params parameter will be an array containing the $model, $key, and $index.

'columns' => [
    [
        'class' => '\kartik\grid\FormulaColumn',
        'value' => function ($model, $key, $index, $widget) {
            $p = compact('model', 'key', 'index');
            // Write your formula below
            return $widget->col(3, $p) + $widget->col(4, $p);
        }
    ]
]

Note

The BooleanColumn supports various grid grouping properties. Refer the Grid Grouping section for details.

This is a new grid column class that extends the \kartik\grid\DataColumn class. It automatically converts boolean data (true/false) values to user friendly indicators or labels (that are configurable). The following are new features added since release v1.6.0:

  • BooleanColumn icons have been setup as ICON_ACTIVE and ICON_INACTIVE constants in GridView.
You would need to set the following parameters for setting up this column:
  • format: string|array, in which format should the value of each data model be displayed as (e.g. "raw", "text", "html", ['date', 'php:Y-m-d']). Supported formats are determined by the GridView::formatter|formatter used by the GridView. Default format is "text" which will format the value as an HTML-encoded plain text when \yii\i18n\Formatter is used as the GridView::$formatter|formatter of the GridView. Note that this is a property available only in kartik\grid\SerialColumn and not the yii\grid\DataColumn.

  • xlFormat: string, the cell format for EXCEL exported content. This will override any auto set format due to GridView::autoXlFormat. Note that excel cell formats needs to be set using mso-number-format specifications. It is important that you must set the format property for this to work effectively. Refer the Excel Export Formatting section for details.

  • hidden: boolean whether the entire column is hidden from display but displayed in your grid export (the opposite of hiddenFromExport) . This is different than the visible property, in the sense,

  • xlFormat: string, the cell format for EXCEL exported content. This will override any auto set format due to GridView::autoXlFormat. Note that excel cell formats needs to be set using mso-number-format specifications. It is important that you must set the format property for this to work effectively. Refer the Excel Export Formatting section for details.

  • hidden: boolean whether the entire column is hidden from display but displayed in your grid export (the opposite of hiddenFromExport) . This is different than the visible property, in the sense, that if this is true the column is rendered, but hidden from display. This will allow you to still export the column using the export function.

  • hiddenFromExport: boolean whether the entire column is hidden from export but shown on display (the opposite of hidden). Defaults to false.

  • trueLabel: string the label for the true value. Defaults to 'Active'.

  • falseLabel: string the label for the false value. Defaults to 'Inactive'.

  • trueIcon: string the icon/indicator that will be displayed when the value is true. If the GridView bootstrap property is set to true, it will default to <span class="glyphicon glyphicon-ok text-success"></span> For other cases when this is null or not set, this will default to the trueLabel.

  • falseIcon: string the icon/indicator that will be displayed when the value is false. If the GridView bootstrap property is set to true, it will default to <span class="glyphicon glyphicon-remove text-danger"></span> For other cases when this is null or not set, this will default to the falseLabel.

  • showNullAsFalse: boolean whether to display the falseIcon if cell value is null. Defaults to false

The following parameters are similar to the DataColumn settings. Default values for these parameters have been carefully set for usage in most scenarios, thus accelerating development.

  • hAlign: string, defaults to GridView::ALIGN_CENTER

  • noWrap: boolean, defaults to false

  • width: string, defaults to 90px

  • pageSummary: boolean, defaults to false

  • filter: array, this is an array which is auto generated based on trueLabel and falseLabel as: [true=>$trueLabel, false=>$falseLabel]

  • format: string, the grid column format. Defaults to 'raw'

'columns' => [
    [
        'class' => '\kartik\grid\BooleanColumn',
        'trueLabel' => 'Yes', 
        'falseLabel' => 'No'
    ]
]

This is a new grid column that works similar to the CheckboxColumn, but allows and restricts only a single row to be selected using radio inputs. In addition, it includes a header level clear button to clear the selected rows. It automatically works with the new pageSummary and includes a default styling to work for many scenarios. The column extends the default \yii\grid\Column, so all the properties for the default \yii\grid\Column class will be applicable. The additional properties available for this column are:

  • name: string the name of the radio input fields. Defaults to kvradio.

  • showClear: boolean whether to show the clear button in the header to clear the selected rows and radio. Defaults to true.

  • clearOptions: array the HTML attributes for the clear button in the header. Defaults to ['class'=>'close', 'title'=>'Clear selection']. The following special option is recognized:

    • label: string the label for the button. Defaults to &times;.

  • radioOptions: array|Closure this can either be an array of attributes or an anonymous function (Closure) that returns such an array. The signature of the function should be function ($model, $key, $index, $column), where $model, $key, and $index refer to the model, key and index of the row currently being rendered and $column is a reference to the RadioColumn object. A function may be used to assign different attributes to different rows based on the data in that row. Specifically if you want to set a different value for the radio, you can use this option in the following way (in this example using the name attribute of the model):

    'radioOptions' => function($model, $key, $index, $column) {
        return ['value' => $model->name];
    }
    

    Refer \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.

  • hidden: boolean whether the column is hidden from display. This is different than the visible property, in the sense, that if this is true the column is rendered, but hidden from display. This will allow you to still export the column using the export function.

  • hiddenFromExport: boolean whether the entire column is hidden from export but shown on display (the opposite of hidden). Defaults to true.

  • rowHighlight: boolean whether to highlight the row when radio is checked. Defaults to true.

  • rowSelectedClass: string the CSS class to apply to the row when rowHighlight is true. Defaults to GridView::TYPE_DANGER.

The following parameters are similar to the DataColumn settings. Default values for these parameters have been carefully set for usage in most scenarios, thus accelerating development.

  • hAlign: Defaults to GridView::ALIGN_CENTER

  • vAlign: Defaults to GridView::ALIGN_MIDDLE

  • noWrap: boolean whether to force no wrapping on all table cells for the column. This will automatically set the header, body, footer, and page summary to not wrap using the white wrap CSS style. Defaults to false.

  • width: Defaults to 50px

  • pageSummary: Defaults to false

  • pageSummaryOptions: Defaults to []

  • hidePageSummary: Defaults to false

  • mergeHeader: Defaults to true

'columns' => [
    [
        'class' => '\kartik\grid\RadioColumn'
    ]
]

You can listen to the following jQuery events via javascript, to capture the rows selected via the radio column.

  • grid.radiochecked: Triggered when a row is selected using the radio input.

  • grid.radiocleared: Triggered when a radio input is cleared using the clear button on the header.

Both of the events returns the following parameters for access:

  • key: string, the primary key value for the row

  • val: string, the value of the selected radio input

For example

var $grid = $('#grid-id'); // your grid identifier 

$grid.on('grid.radiochecked', function(ev, key, val) {
    console.log("Key = " + key + ", Val = " + val);
});

$grid.on('grid.radiocleared', function(ev, key, val) {
    console.log("Key = " + key + ", Val = " + val);
});

The default Yii \yii\grid\CheckboxColumn column has been enhanced with various additional parameters to work with the new pageSummary and a default styling to work for many scenarios. The following additional properties are available:

  • hidden: boolean whether the column is hidden from display. This is different than the visible property, in the sense, that if this is true the column is rendered, but hidden from display. This will allow you to still export the column using the export function.

  • hiddenFromExport: boolean whether the entire column is hidden from export but shown on display (the opposite of hidden). Defaults to true.

  • rowHighlight: boolean whether to highlight the row when checkbox is checked. Defaults to true.

  • rowSelectedClass: string the CSS class to apply to the row when rowHighlight is true. Defaults to GridView::TYPE_DANGER.

The following properties are similar to the DataColumn settings. Default values for these parameters have been carefully set for usage in most scenarios, thus accelerating development.

  • hAlign: Defaults to GridView::ALIGN_CENTER

  • vAlign: Defaults to GridView::ALIGN_MIDDLE

  • noWrap: boolean whether to force no wrapping on all table cells for the column. This will automatically set the header, body, footer, and page summary to not wrap using the white wrap CSS style. Defaults to false.

  • width: Defaults to 50px

  • pageSummary: Defaults to false

  • pageSummaryOptions: Defaults to []

  • hidePageSummary: Defaults to false

  • mergeHeader: Defaults to true

'columns' => [
    [
        'class' => '\kartik\grid\CheckboxColumn'
    ]
]

You can get the checked rows very similar to how you would do it for a default yii\grid\CheckboxColumn. Users may click on the checkboxes to select rows of the grid. The selected rows may be obtained by calling the following JavaScript code:

var keys = $('#grid').yiiGridView('getSelectedRows');
// keys is an array consisting of the keys associated with the selected rows

The default \yii\grid\ActionColumn has been enhanced with various additional parameters to have a dropdown action menu and work with the new pageSummary and a default styling to work for many scenarios. The following are new features added since release v1.6.0:

  • ActionColumn content by default has been disabled to appear in export output. The skip-export CSS class has been set as default in headerOptions and contentOptions.
The following additional parameters are available:

  • hidden: boolean whether the column is hidden from display. This is different than the visible property, in the sense, that if this is true the column is rendered, but hidden from display. This will allow you to still export the column using the export function.

  • hiddenFromExport: boolean whether the entire column is hidden from export but shown on display (the opposite of hidden). Defaults to true.

  • dropdown: boolean whether the action buttons are to be displayed as a dropdown button menu. Applicable only if the grid bootstrap property is set to true. Defaults to false.

  • dropdownOptions: array the HTML attributes for the Dropdown main container. Applicable if dropdown is set to true. Defaults to ['class'=>'dropdown']. To align a dropdown at the right edge of the page container, you set this to:

    dropdownOptions => ['class' => 'pull-right']
    
  • dropdownMenu: array the HTML attributes for the Dropdown menu container. Applicable if dropdown is set to true. Defaults to ['class'=>'text-left']

  • dropdownButton: array HTML attributes for the Dropdown actions button. Applicable if dropdown is set to true. Defaults to ['class'=>'btn btn-default']. The following additional options are recognized:

    • label: string, the label for the action dropdown button. This is not html encoded. Defaults to Actions.

    • caret: string, the caret symbol to be appended to the dropdown button. This is not html encoded. Defaults to <span class="caret"></span>.

  • viewOptions: array HTML attributes for the view action button. The following additional option is recognized:

    • label: string, the label for the view action button. This is not html encoded.

  • updateOptions: array HTML attributes for the update action button. The following additional option is recognized:

    • label: string, the label for the update action button. This is not html encoded.

  • deleteOptions: array HTML attributes for the delete action button. The following additional option is recognized:

    • label: string, the label for the delete action button. This is not html encoded.

  • buttons: array button rendering callbacks. The array keys are the button names (without curly brackets), and the values are the corresponding button rendering callbacks. The callbacks should use the following signature:

    function ($url, $model) {
        // return the button HTML code
    }
    

    where, $url is the URL that the column creates for the button, and $model is the model object being rendered for the current row. Normally this generates the HTML link to display for each action button. If the dropdown property is set to true, you must return this as a link content enclosed within <li> tags. If you wish to display a dropdown separator in between just return <li class="divider"></li>.

The following parameters are similar to the DataColumn settings. Default values for these parameters have been carefully set for usage in most scenarios, thus accelerating development.

  • hAlign: Defaults to GridView::ALIGN_CENTER

  • vAlign: Defaults to GridView::ALIGN_MIDDLE

  • noWrap: boolean whether to force no wrapping on all table cells for the column. This will automatically set the header, body, footer, and page summary to not wrap using the white wrap CSS style. Defaults to false.

  • width: Defaults to 80px

  • pageSummary: Defaults to false

  • pageSummaryOptions: Defaults to []

  • hidePageSummary: Defaults to false

  • mergeHeader: Defaults to true

'columns' => [
    [
        'class' => '\kartik\grid\ActionColumn',
        'deleteOptions' => ['label' => '<i class="glyphicon glyphicon-remove"></i>']
    ]
]

The default Yii \yii\grid\SerialColumn column has been enhanced with various additional parameters to work with the new pageSummary and a default styling to work for many scenarios.

The following parameters are similar to the DataColumn settings. Default values for these parameters have been carefully set for usage in most scenarios, thus accelerating development.

  • format: string|array, in which format should the value of each data model be displayed as (e.g. "raw", "text", "html", ['date', 'php:Y-m-d']). Supported formats are determined by the GridView::formatter|formatter used by the GridView. Default format is "text" which will format the value as an HTML-encoded plain text when \yii\i18n\Formatter is used as the GridView::$formatter|formatter of the GridView. Note that this is a property available only in kartik\grid\SerialColumn and not the yii\grid\DataColumn.

  • xlFormat: string, the cell format for EXCEL exported content. This will override any auto set format due to GridView::autoXlFormat. Note that excel cell formats needs to be set using mso-number-format specifications. It is important that you must set the format property for this to work effectively. Refer the Excel Export Formatting section for details.

  • hidden: boolean whether the column is hidden from display. This is different than the visible property, in the sense, that if this is true the column is rendered, but hidden from display. This will allow you to still export the column using the export function.

  • hiddenFromExport: boolean whether the entire column is hidden from export but shown on display (the opposite of hidden). Defaults to false.

  • hAlign: Defaults to GridView::ALIGN_CENTER

  • vAlign: Defaults to GridView::ALIGN_MIDDLE

  • noWrap: boolean whether to force no wrapping on all table cells for the column. This will automatically set the header, body, footer, and page summary to not wrap using the white wrap CSS style. Defaults to false.

  • width: Defaults to 50px

  • pageSummary: Defaults to false

  • pageSummaryFunc: Defaults to GridView::F_COUNT

  • pageSummaryOptions: Defaults to []

  • hidePageSummary: Defaults to false

  • mergeHeader: Defaults to true

  • header: Parent setting. Defaults to #

'columns' => [
    [
        'class' => '\kartik\grid\SerialColumn'
    ]
]

yii2-grid is released under the BSD 3-Clause License. See the bundled LICENSE.md for details.