Krajee
Thankful to Krajee! BUY A COFFEEor to get more out of us.

The yii2-dynagrid module is a great complementary addition to the kartik-v/yii2-grid module, enhancing it with personalization features. It turbo charges your grid view by making it dynamic and personalized for each user. It allows users the ability to set and save their own grid configuration. The major features provided by this module are:

  • Personalize, set, and save grid page size at runtime. You can set the minimum and maximum page size allowed.

  • Personalize, set, and save grid data filters at runtime. A user can define and save his/her own personalized grid data filters.

  • Personalize, set, and save grid column sorts at runtime. A user can define and save his/her own personalized grid column sorts.

  • Personalize the grid columns display through drag and drop. Reorder grid columns and set the visibility of needed columns, and allow users to save this setting. Control which columns can be reordered by users through predefined columns setup. Predetermine which of your desired columns will be always fixed to the left or right by default.

  • Personalize grid appearance and set the grid theme. This will offer advanced customization to the grid layout. It allows users to virtually style grid anyway they want, based on how you define themes and extend them to your users. Since the extension uses the yii2-grid extension, it offers all the styling options the yii2-grid extension provides including the various grid column enhancements, bootstrap panels, and other grid styles. This will allow you to easily setup themes for users in many ways. You have an ability to setup multiple themes in your module configuration, and allow users to select one of them. The extension by default includes some predefined themes for you to get started.

  • Allow you to save the dynamic grid configuration specific to each user or global level. Implements a DynaGridStore object to manage dynagrid personalizations independent of storage. One of the following storage options are made available to store the personalized grid configuration:

    • Session Storage (default)

    • Cookie Storage

    • Database Storage

  • The extension automatically validates and loads the saved configuration based on the stored settings.

Note: The latest version of the module v1.2.0 has been released on 25-Oct-2014. Refer the CHANGE LOG for details.

View a complete demo.

Warning

You need to be careful, in case you are using the new \kartik\grid\FormulaColumn in your grid layout. The reordering of columns by users will render your formulae invalid, since the column indices will change. It is recommended, you set the order of all such formulae columns and its dependencies to DynaGrid::ORDER_FIX_LEFT, so that such column positions are pre-fixed.

Tip

Not seeing the updated content on this page! Hard refresh your browser to clean cache for this page (e.g. SHIFT-F5 on Windows Chrome)

DynaGrid supports configuration of the bootstrap library version so that you can use this either with any Bootstrap version 3.x and above. For setting up the bootstrap version for your extension, you can configure the DynaGrid::bsVersion property to one of the following.

  • To use with bootstrap 3 library - you can set DynaGrid::bsVersion property to any string starting with 3 (e.g. 3 or 3.3.7 or 3.x)

  • To use with bootstrap 4 library - you can set DynaGrid::bsVersion property to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

  • To use with bootstrap 5 library - you can set DynaGrid::bsVersion property to any string starting with 5 (e.g. 5 or 5.1.0 or 5.x)

The following sections describe the pre-requisites for enabling Bootstrap library specific version support in your application and other related controls/overrides.

Global Bootstrap Version


Generally, you may also want to set a default version globally for all Krajee Extensions (instead of setting it for each widget or extension separately). In order to do this, you can setup the bsVersion property within Yii 2 application params (i.e. Yii::$app->params['bsVersion']). To set this up, add this section of code to your application params configuration file (e.g. config/params.php):

'params' => [
    'bsVersion' => '5.x', // this will set globally `bsVersion` to Bootstrap 5.x for all Krajee Extensions
    // other settings
    // 'adminEmail' => 'admin@example.com'
]

If DynaGrid::bsVersion property is set, in addition to Yii::$app->params['bsVersion'], the extension level setting (DynaGrid::bsVersion property) will override the Yii::$app->params['bsVersion']. If DynaGrid::bsVersion property is not set, and Yii::$app->params['bsVersion'] is also not set, DynaGrid::bsVersion property will default to 3.x (i.e. Bootstrap 3.x version will be assumed as default).

Yii2 Bootstrap Dependency


You need to install one of yiisoft/yii2-bootstrap or yiisoft/yii2-bootstrap4 or yiisoft/yii2-bootstrap5 extensions manually in your application to enable Bootstrap 3.x or 4.x or 5.x functionality respectively. This dependency has not been pre-built into the composer configuration for Krajee extensions, to allow better control to the developers in configuring their bootstrap library version. If bsVersion is set to 5.x and yiisoft/yii2-bootstrap5 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap5 extension. If bsVersion is set to 4.x and yiisoft/yii2-bootstrap4 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap4 extension. Similarly, if bsVersion is set to 3.x and yiisoft/yii2-bootstrap is not installed, an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap extension.

To install yiisoft/yii2-bootstrap5, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap5": "@dev"

To install yiisoft/yii2-bootstrap4, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap4": "@dev"

To install yiisoft/yii2-bootstrap, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap": "@dev"

Override Bootstrap CSS/JS


The Krajee extension asset bundle(s) by default depend on one of the following asset bundles to load the Bootstrap CSS and JS:

  • yii\bootstrap\BootstrapAsset and/or yii\bootstrap\BootstrapPluginAsset for bootstrap 3.x (bsVersion = 3 setting)

  • yii\bootstrap4\BootstrapAsset and/or yii\bootstrap4\BootstrapPluginAsset for bootstrap 4.x ( bsVersion = 4 setting)

  • yii\bootstrap5\BootstrapAsset and/or yii\bootstrap5\BootstrapPluginAsset for bootstrap 5.x (bsVersion = 5 setting)

This is controlled by the property bsDependencyEnabled within the asset bundle (which defaults to true). One can override this and prevent the default yii2 bootstrap assets (CSS & JS) from loading by doing one or all of the following:

  • Global Override: Set Yii::$app->params['bsDependencyEnabled'] to false in your Yii 2 application config params.php. This setting will be applied for all Krajee Extension Asset Bundles that depend on Bootstrap assets.

    'params' => [
        'bsDependencyEnabled' => false, // this will not load Bootstrap CSS and JS for all Krajee extensions
        // you need to ensure you load the Bootstrap CSS/JS manually in your view layout before Krajee CSS/JS assets
        //
        // other params settings below
        // 'bsVersion' => '5.x',
        // 'adminEmail' => 'admin@example.com'
    ]
    
  • Asset Bundle Specific Override: Set bsDependencyEnabled to false for the specific asset bundle within Yii2 Asset Manager component in your Yii 2 application config file.

    // ...
    'components' => [
        'assetManager' => [
            'bundles' => [
                'kartik\form\ActiveFormAsset' => [
                    'bsDependencyEnabled' => false // do not load bootstrap assets for a specific asset bundle
                ],
            ],
        ],
    ],
    

Note

When setting bsDependencyEnabled to false, you need to ensure that your app code/view layout loads the Bootstrap CSS and JS on your view before the Krajee CSS/JS are loaded to ensure that the Krajee extension JS plugins and CSS styles do not get broken.

Icons for Bootstrap


Bootstrap 5.x / 4.x does not include glyphicons or any other icons framework bundled with the library. Krajee extensions therefore will use Font Awesome 5.x icons instead of glyphicons when working with Bootstrap 5.x / 4.x. You can download Font Awesome 5.x icons from the icons website. Alternatively, you can load the free version of Font Awesome from their CDN.

For Krajee extensions and demos, the Font Awesome Free version is used and loaded as the Icons Display Package on all the Yii2 demo layouts. To include font awesome assets on your page, include the following markup on the HEAD section of your view layout file, when bsVersion is set to 4.x or 5.x.

  • Option 1: Font CSS version of Font Awesome:

    <!-- on your view layout file HEAD section -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
    
  • Option 2: SVG / JS version of Font Awesome (recommended for cleaner scaling vector icons and features like icon layers):

    <!-- on your view layout file HEAD section -->
    <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" crossorigin="anonymous"></script>
    

    Alternatively, you can use the FontAwesomeAsset from the kartik-v/yii2-icons package to load the SVG/JS version.

    // on your view layout file
    use kartik\icons\FontAwesomeAsset;
    FontAwesomeAsset::register($this);
    

The yii2-dynagrid extension can be installed automatically or manually using one of these options:

Composer Package Manager Recommended


Installation via Composer is the recommended and most easy option to install Krajee Yii2 extensions. You can install yii2-dynagrid via composer package manager. Either run:

$ php composer.phar require kartik-v/yii2-dynagrid "dev-master"

or add:

"kartik-v/yii2-dynagrid": "dev-master"

to your application's composer.json file.

Manual Install


You may also manually install the extension to your project (in case your composer install does not work). Just download the source ZIP or TAR ball and extract the extension asset files and folders into your project. You may need to install dependencies manually and also set the namespaces to the extensions in your Yii2 extensions configurations manually.

Before you start using the DynaGrid widget, you must setup and add the module to your configuration file. The module must be named dynagrid as shown below. In addition, you must also register the gridview module as described yii2-grid documentation.
'modules'=>[
   'dynagrid'=> [
        'class'=>'\kartik\dynagrid\Module',
        // other module settings
    ],
    'gridview'=> [
        'class'=>'\kartik\grid\Module',
        // other module settings
    ],
];
The module can take in the following parameters:
  • bsVersion: string | int, the bootstrap library version to be used for the extension. Refer the Bootstrap Info section for details and pre-requisites on setting this property.

    • To use with Bootstrap library - you can set this to any string starting with 3 (e.g. 3 or 3.3.7 or 4.x / 3.x)

    • To use with bootstrap 4 - you can set this to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

    • To use with bootstrap 5 - you can set this to any string starting with 4 (e.g. 5 or 5.1.0 or 5.x)

  • bsColCssPrefixes: array, the bootstrap grid column css prefixes mapping, the key is the bootstrap versions, and the value is an array containing the sizes and their corresponding grid column css prefixes. The class using this trait, must implement kartik\base\BootstrapInterface. If not set will default to:.

    [
       3 => [
          self::SIZE_X_SMALL => 'col-xs-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-lg-',
          self::SIZE_XX_LARGE => 'col-lg-',
       ],
       4 => [
          self::SIZE_X_SMALL => 'col-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-xl-',
          self::SIZE_XX_LARGE => 'col-xl-',
       ],
       5 => [
          self::SIZE_X_SMALL => 'col-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-xl-',
          self::SIZE_XX_LARGE => 'col-xxl-',
       ],
    ];
    
  • cookieSettings: array, the cookie settings when you are using 'cookie' as storage method in the DynaGrid widget. Refer yii\web\Cookie settings for details on properties supported. Defaults to ['httpOnly'=>true, 'expire'=>time() + 8640000]

  • dbSettings: array, the settings for the database if you are using 'db' as storage method in the DynaGrid widget. The following properties are recognized:

    • tableName: string, the name of the table which will be used for storage. Defaults to tbl_dynagrid.

    • idAttr: string, the name of the id column in the table. Defaults to id.

    • filterAttr: string, the attribute name for the filter setting id. Defaults to filterId.

    • sortAttr: string, the attribute name for the filter setting id. Defaults to sortId.

    • dataAttr: string, the name of the dataAttr column in the table. Defaults to data.

    You must create the above table in your database before you start using the widget. Refer the data folder of this repository for an example MYSQL script. An example of the table creation script for MYSQL database is shown below:

    CREATE TABLE `tbl_dynagrid` (
      `id` varchar(100) NOT NULL COMMENT 'Unique dynagrid setting identifier',
      `filter_id` varchar(100) COMMENT 'Filter setting identifier',
      `sort_id` varchar(100) COMMENT 'Sort setting identifier',
      `data` varchar(5000) DEFAULT NULL COMMENT 'Json encoded data for the dynagrid configuration',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Dynagrid personalization configuration settings';
    
  • dbSettingsDtl: array, the settings for the detail database table to store the dynagrid filter and sort settings. The following properties are recognized:

    • tableName: string, the name of the table which will be used for storage. Defaults to tbl_dynagrid_dtl.

    • idAttr: string, the name of the id column in the table. Defaults to id.

    • categoryAttr: string, the attribute name for the detail category (values currently possible are filter or sort). Defaults to category.

    • nameAttr: string, the attribute name for for the filter or sort name. Defaults to name.

    • dataAttr: string, the name of the dataAttr column in the table. Defaults to data.

    • dynaGridId: string, the attribute name for the dynagrid identifier. Defaults to dynagrid_id.

    You must create the above table in your database before you start using the widget. Refer the data folder of this repository for an example MYSQL script. An example of the table creation script for MYSQL database is shown below:

    CREATE TABLE `tbl_dynagrid_dtl` (
      `id` varchar(100) NOT NULL COMMENT 'Unique dynagrid detail setting identifier',
      `category` varchar(10) NOT NULL COMMENT 'Dynagrid detail setting category "filter" or "sort"',
      `name` varchar(150) NOT NULL COMMENT 'Name to identify the dynagrid detail setting',
      `data` varchar(5000) DEFAULT NULL COMMENT 'Json encoded data for the dynagrid detail configuration',
      `dynagrid_id` varchar(100) NOT NULL COMMENT 'Related dynagrid identifier',
      PRIMARY KEY (`id`),
      UNIQUE KEY `tbl_dynagrid_dtl_UK1` (`name`,`category`,`dynagrid_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Dynagrid detail configuration settings';
    

    You can also create FOREIGN KEY constraints as shown below

    ALTER TABLE `tbl_dynagrid`
    ADD CONSTRAINT `tbl_dynagrid_FK1` 
    FOREIGN KEY (`filter_id`) 
    REFERENCES `tbl_dynagrid_dtl` (`id`) 
    , ADD INDEX `tbl_dynagrid_FK1` (`filter_id` ASC);
    
    ALTER TABLE `tbl_dynagrid`
    ADD CONSTRAINT `tbl_dynagrid_FK2` 
    FOREIGN KEY (`sort_id`) 
    REFERENCES `tbl_dynagrid_dtl` (`id`) 
    , ADD INDEX `tbl_dynagrid_FK2` (`sort_id` ASC);
    
  • dynaGridOptions: array, the default global options for the DynaGrid widget. See the DynaGrid documentation section for the properties supported.

  • configView: string, the view file name for displaying and saving the dynagrid configuration. You can override this with your own view, if you want to display your own layout. Defaults to config, which will bascially be this file in your vendor folder: kartik-v/yii2-dynagrid/views/config.php.

  • settingsView: string, the view file name for displaying and saving the dynagrid detail settings for filter and sort. You can override this with your own view, if you want to display your own layout. Defaults to settings, which will bascially be this file in your vendor folder: kartik-v/yii2-dynagrid/views/settings.php.

  • settingsConfigAction: mixed, the action URL for displaying the dynagrid detail configuration settings on the dynagrid detail settings form. Defaults to /dynagrid/settings/get-config.

  • themeConfig: array, the configuration of various themes for the grid configuration. You must set this in $themeName=>$themeSettings format, where:

    • $themeName: string, is a unique name to identify your theme, and

    • $themeSettings: array, will be an array of the configuration properties as supported by \kartik\grid\GridView widget.

    You can also set these themes in a separate php file and call the config here using PHP require. The widget by default has the following themes pre-configured:

    [
        'simple-default'=>['panel'=>false,'bordered'=>false,'striped'=>false,'hover'=>true,'layout'=>Module::LAYOUT_1],
        'simple-bordered'=>['panel'=>false,'striped'=>false,'hover'=>true,'layout'=>Module::LAYOUT_1],
        'simple-condensed'=>['panel'=>false,'striped'=>false,'condensed'=>true,'hover'=>true,'layout'=>Module::LAYOUT_1],
        'simple-striped'=>['panel'=>false,'layout'=>Module::LAYOUT_1],
        'panel-default'=>['panel'=>['type'=>GridView::TYPE_DEFAULT,'before'=>Module::LAYOUT_2]],
        'panel-primary'=>['panel'=>['type'=>GridView::TYPE_PRIMARY,'before'=>Module::LAYOUT_2]],
        'panel-info'=>['panel'=>['type'=>GridView::TYPE_INFO,'before'=>Module::LAYOUT_2]],
        'panel-danger'=>['panel'=>['type'=>GridView::TYPE_DANGER,'before'=>Module::LAYOUT_2]],
        'panel-success'=>['panel'=>['type'=>GridView::TYPE_SUCCESS,'before'=>Module::LAYOUT_2]],
        'panel-warning'=>['panel'=>['type'=>GridView::TYPE_WARNING,'before'=>Module::LAYOUT_2]],
    ]
    

    where

    • Module::LAYOUT_1 is "<hr>{dynagrid}<hr> {summary} {items} {pager}"

    • Module::LAYOUT_2 is "{dynagrid}"

    Note

    The {dynagrid} tag in your layout template will be replaced by the DynaGrid widget, which will render the grid personalization configuration toggle button and the configuration form as a bootstrap modal dialog.
  • defaultTheme: string, the default theme to use for the DynaGrid widget. Defaults to panel-primary.

  • defaultPageSize: integer, the default page size to use for the DynaGrid widget. Defaults to 10. Note that setting this to 0 means an unlimited page size.

  • minPageSize: integer, the minimum page size that can be setup by users using the DynaGrid configuration form. Defaults to 5. Note a 0 value means an unlimited page size.

  • maxPageSize: integer, the maximum page size that can be setup by users using the DynaGrid configuration form. Defaults to 50.

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

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

Note:

The module has i18n / translation features enabled. You can edit the kvdynagrid.php file in the messages folder for your language by submitting a new pull request.
Once you have setup the module, the DynaGrid widget will be useful for rendering your gridview with the dynagrid configuration button and form. The widget supports the configuration properties mentioned below.

Note

Configuring a pagesize to 0 means an unlimited pagesize and will display all records on one page.
These properties if not set, will be defaulted from the module level dynaGridOptions setting.
  • bsVersion: string | int, the bootstrap library version to be used for the extension. Refer the Bootstrap Info section for details and pre-requisites on setting this property.

    • To use with Bootstrap library - you can set this to any string starting with 3 (e.g. 3 or 3.3.7 or 4.x / 3.x)

    • To use with bootstrap 4 - you can set this to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

    • To use with bootstrap 5 - you can set this to any string starting with 4 (e.g. 5 or 5.1.0 or 5.x)

    NOTE If this property is NOT SET, then this property will default to the bsVersion property set at the Module level which will override the Yii::$app->params['bsVersion'] setting.

  • bsColCssPrefixes: array, the bootstrap grid column css prefixes mapping, the key is the bootstrap versions, and the value is an array containing the sizes and their corresponding grid column css prefixes. The class using this trait, must implement kartik\base\BootstrapInterface. If not set will default to:.

    [
       3 => [
          self::SIZE_X_SMALL => 'col-xs-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-lg-',
          self::SIZE_XX_LARGE => 'col-lg-',
       ],
       4 => [
          self::SIZE_X_SMALL => 'col-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-xl-',
          self::SIZE_XX_LARGE => 'col-xl-',
       ],
       5 => [
          self::SIZE_X_SMALL => 'col-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-xl-',
          self::SIZE_XX_LARGE => 'col-xxl-',
       ],
    ];
    
  • storage: string, the type of storage for storing the dynagrid configuration, when user applies/saves the configuration. Should be one of the following:

    • 'session' or DynaGrid::TYPE_SESSION: Save the config in a session variable for the current session.

    • 'cookie' or DynaGrid::TYPE_COOKIE: Save the config in a cookie for retrieval. You need to setup the Module::cookieSettings property to control the cookie expiry and other settings.

    • 'db' or DynaGrid::TYPE_DB: Save the config to a database. You need to setup the Module::dbSettings and Module::dbSettingsDtl properties to to setup the database table and attributes for storage.

  • theme: string, the initial default theme to be set for the widget. If not provided will take in the defaultTheme setting from the module..

  • userSpecific: boolean, whether settings are stored specific to each user. Defaults to true.

  • dbUpdateNameOnly: boolean, whether to update only the name, when editing and saving a filter or sort. This is applicable only when storage is set to Dynagrid::TYPE_DB. Defaults to false. If set to false, it will also overwrite the current filter/sort settings and if set to true, only the filter/sort name will be updated.

  • showPersonalize: boolean, whether to show the personalize button. Defaults to true.

  • showSort: boolean, whether to show the sort save widget button. Defaults to true.

  • enableMultiSort: boolean, whether to enable multiple attribute sorting. Defaults to true.

  • showFilter: boolean, whether to show the filter save widget button. Defaults to true.

  • allowPageSetting: boolean, whether to allowsetup of the pagination in the personalize grid form. Defaults to true. This will default to false, if you set pagination to false for the gridOptions['dataProvider'].

  • allowThemeSetting: boolean, whether to allow display/setup of the theme in the personalize grid form. Defaults to true.

  • allowFilterSetting: boolean, whether to allow display/setup of the filter in the personalize grid form. Defaults to true.

  • allowSortSetting: boolean, whether to allow display/setup of the sort in the personalize grid form. Defaults to true. This will default to false, if you set sort to false for the gridOptions['dataProvider'].

  • gridOptions: array, widget options for \kartik\grid\GridView that will be rendered by the DynaGrid widget. Many settings here are defaulted as per the chosen theme setting in themeConfig of \kartik\dynagrid\Module.

    Note

    The {dynagrid} tag should be embedded in one of the following sections:

    • gridOptions['panel']['before']

    • gridOptions['panel']['after']

    • gridOptions['layout']

    The widget will automatically replace the {dynagrid} tag in the above section(s), with the DynaGrid personalization configuration toggle button and the configuration form as a bootstrap modal dialog. For example, you can setup your customized before content in your grid panel like below:

    echo DynaGrid::widget([
        'columns' => $columns,
        'theme'=>'panel-warning',
        'gridOptions'=>[
            'dataProvider'=>$dataProvider,
            'filterModel'=>$searchModel,
            'showPageSummary'=>true,
            'panel'=>[
                'heading'=>'<h3 class="panel-title"><i class="fas fa-book">  Library',
                'before'=>'{dynagrid}' . Html::a('Custom Button', '#', ['class'=>'btn btn-secondary btn-default'])
            ],
        ]
    ]);
  • matchPanelStyle: boolean, whether the DynaGrid configuration button class should match the grid panel style. Defaults to true.

  • toggleButtonGrid: array, the HTML attributes for the toggle button which will render the DynaGrid configuration form within a Bootstrap Modal container. Refer yii\bootstrap\Modal documentation for properties supported. The following default settings are available:

    • label: string, the label to be displayed for the button. Defaults to <span class="fas fa-wrench"></span>.

    • title: string, the title to be displayed for the button on hover. Defaults to Personalize grid settings.

    • data-pjax: boolean, whether to trigger a pjax action on click. Defaults to false.

  • toggleButtonFilter: array, the HTML attributes for the filter configuration button which will render the Filter settings form within a Bootstrap Modal container. The following default settings are available:

    • label: string, the label to be displayed for the button. Defaults to <span class="fas fa-filter"></span>.

    • title: string, the title to be displayed for the button on hover. Defaults to Save / edit grid filter.

    • data-pjax: boolean, whether to trigger a pjax action on click. Defaults to false.

  • toggleButtonSort: array, the HTML attributes for the sort configuration button which will render the Sort settings form within a Bootstrap Modal container. The following default settings are available:

    • label: string, the label to be displayed for the button. Defaults to <span class="fas fa-sort"></span>.

    • title: string, the title to be displayed for the button on hover. Defaults to Save / edit grid sort.

    • data-pjax: boolean, whether to trigger a pjax action on click. Defaults to false.

  • options: array, the HTML attributes for the DynaGrid widget container. You must mandatorily setup a unique identifier for the DynaGrid widget by setting a value for the id property. For example: 'options' => ['id' => 'dynagrid-1']/

  • sortableOptions: array, the widget settings for the Sortable widget. The widget uses \kartik\sortable\Sortable widget to enable dragging and dropping of columns for reordering. Refer the Sortable widget documentation for supported properties for the widget.

  • sortableHeader: array, the HTML attributes for the sortable columns header. Defaults to ['class'=>'alert alert-info dynagrid-column-header'].

  • columns: array, the grid view columns configuration. The column properties as supported by \kartik\grid\GridView are also supported here. This widget allows an important additional property order (string). The columns['order']can be one of the following:

    • 'fixleft' or DynaGrid::ORDER_FIX_LEFT which will fix the column order to the left part of the grid and prevent the user to reorder or change this column setting.

    • 'fixright' or DynaGrid::ORDER_FIX_RIGHT which will fix the column order to the right part of the grid and prevent the user to reorder or change this column setting.

    • 'middle' or DynaGrid::ORDER_MIDDLE which will be the columns in the middle part of the grid. This is the default setting for order if implicitly not set. The DynaGrid::ORDER_MIDDLE order setting for a column, will allow the gridview user to reorder and control display of the column.

    Note

    You can set the visible property of a column to false, to not show it by default in the grid layout.
  • submitMessage: string, the message to display after applying and submitting the configuration and until refreshed grid is reloaded. Defaults to Saving and applying configuration.

  • deleteMessage: string, the message to display after deleting the configuration and until refreshed grid is reloaded. Defaults to Trashing all personalizations.

  • messageOptions: array, the HTML attributes for the submission message container.

  • deleteConfirmation: string, the confirmation warning message before deleting a personalization configuration or setting. Defaults to Are you sure you want to delete the setting?.

  • submitButtonOptions: array, the HTML attributes for the save/apply action button. If this is set to false, it will not be displayed. The following special variables are supported:

    • icon: string, the glyphicon suffix class name that will be created as a label for the button. Defaults to save.

    • label: string, the label to be displayed for the action button. Defaults to empty string.

    • title: string, the title to be displayed for the action button on hover. Defaults to Save grid settings.

  • resetButtonOptions: array, the HTML attributes for the reset action button. If this is set to false, it will not be displayed. The following special variables are supported:

    • icon: string, the glyphicon suffix class name that will be created as a label for the button. Defaults to repeat.

    • label: string, the label to be displayed for the action button. Defaults to empty string.

    • title: string, the title to be displayed for the action button on hover. Defaults to Abort any changes and reset settings.

  • deleteButtonOptions: array, the HTML attributes for the reset action button. If this is set to false, it will not be displayed. The following special variables are supported:

    • icon: string, the glyphicon suffix class name that will be created as a label for the button. Defaults to trash.

    • label: string, the label to be displayed for the action button. Defaults to empty string.

    • title: string, the title to be displayed for the action button on hover. Defaults to Remove saved grid setting.

  • iconVisibleColumn: string, the icon that will be displayed for each VISIBLE column heading in the column reordering pane. This is not HTML encoded. To prevent displaying this, set this to a blank or empty character. Defaults to:

    <i class="fas fa-eye-open"></i>
    
  • iconHiddenColumn: string, the icon that will be displayed for each HIDDEN column heading in the column reordering pane. This is not HTML encoded. To prevent displaying this, set this to a blank or empty character. Defaults to:

    <i class="fas fa-eye-close"></i>
    

Usage:

use kartik\widgets\DynaGrid;
use kartik\grid\GridView;
$columns = [
    ['class'=>'kartik\grid\SerialColumn', 'order'=>DynaGrid::ORDER_FIX_LEFT],
    'id',
    'name',
    [
        'attribute'=>'publish_date',
        'filterType'=>GridView::FILTER_DATE,
        'format'=>'raw',
        'width'=>'170px',
        'filterWidgetOptions'=>[
            'pluginOptions'=>['format'=>'yyyy-mm-dd']
        ],
    ],
    [
        'class'=>'kartik\grid\BooleanColumn',
        'attribute'=>'status',
        'vAlign'=>'middle',
    ],
    [
        'class'=>'kartik\grid\ActionColumn',
        'dropdown'=>false,
        'order'=>DynaGrid::ORDER_FIX_RIGHT
    ],
    ['class'=>'kartik\grid\CheckboxColumn', 'order'=>DynaGrid::ORDER_FIX_RIGHT],
];

echo DynaGrid::widget([
    'columns'=>$columns,
    'storage'=>DynaGrid::TYPE_COOKIE,
    'theme'=>'panel-danger',
    'gridOptions'=>[
        'dataProvider'=>$dataProvider,
        'filterModel'=>$searchModel,
        'panel'=>['heading'=>'<h3 class="panel-title">Library</h3>'],
    ],
    'options'=>['id'=>'dynagrid-1'] // a unique identifier is important
]);

Mentioned below are some important pre-requisites for setting up dynagrid. Be sure to read them:

Step 1: Module Setup

You must have setup a module named gridview in your yii config file as per the yii2-grid documentation. In addition, you must also setup the module named dynagrid as described in this section before. You can set module level defaults as described in each module's settings

Step 2: Storage Setup

Ensure you have determined what storage to use. Once decided, ensure you have setup the storage related settings in your dynagrid module. For example dbSettings and dbSettingsDtl for database storage or cookieSettings for cookie storage. Your database tables for db storage must be created as mentioned in the settings before.

Step 3: Filter Setup

The setting up of search model (or filter model) is very important for dynagrid to work well. Your search model must implement a search method as generated by default by gii . In addition, you must change your search function criteria for returning your dataProvider . For example, if your search model class is BookSearch and your source model is Book , your search method should be modified as shown below:

public function search($params)
{
    $query = Book::find();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'pagination' => [
            'pagesize' => 10 // in case you want a default pagesize
        ]
    ]);

    // The following condition is important and must be changed. The $_GET validation
    // is important (or you can use $_POST if you have configured post method).
    // Without this validation saved filters cannot be applied.
    if (isset($_GET['BookSearch']) && !($this->load($params) && $this->validate())) {
        return $dataProvider;
    }

    // the other part below can be as per the default gii code or whatever you need
    $query->andFilterWhere([
        'id' => $this->id,
        'publish_date' => $this->publish_date,
        'status' => $this->status,
        'buy_amount' => $this->buy_amount,
        'sell_amount' => $this->sell_amount,
        'author_id' => $this->author_id,
    ]);

    $query->andFilterWhere(['like', 'name', $this->name])
        ->andFilterWhere(['like', 'color', $this->color]);

    return $dataProvider;
}
Step 4: Sort Setup

The widget by default enables multiple attribute sorting. This is different from the yii default dataProvider setup. In case you wish to change this, you can set enableMultiSort property to false in the DynaGrid widget configuration.

Step 5: Toolbar Setup

The toolbar needs to be explicitly defined for each dynagrid setup. Note that the toolbar configuration is an array of various bootstrap button groups that accepts a combination of array or strings (refer dynagrid settings/options). The following tags are specially replaced:

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

  • {{dynagridFilter}: will be replaced with the dynagrid filter editing button.

  • {{dynagridSort}: will be replaced with the dynagrid sort editing button.

  • {{dynagrid}: will be replaced with the dynagrid main personalization button.

In addition, you can use any other tag that you have also set in replaceTags within gridOptions.

Step 6: Configure Feature Availability

You can configure availability of features to your users. For example use the showFilter or showSort boolean properties to control visibility of the filter or sort buttons. You can set showPersonalize boolean property to control visibility of the main grid personalize button. In addition, you could control allowFilterSetting boolean property to set whether the filter can be changed on the main personalization form. Similarly you can set the allowSortSetting to control display of the sort selector in grid personalization form.

Options With release v1.2.0, the storage of the dynagrid personalization is handled via a separate DynaGridStore object. This is internally used by the DynaGrid widget, and normally not needed for most use cases. However, if you wish to implement an advanced version of DynaGrid or extend the class, you can use this class to manage storage in an object oriented manner. The class allows configuration of these properties:
  • category: string, the category of data to store. Should be one of the following:

    • DynaGridStore::STORE_GRID or 'grid' : if you are storing the grid level personalization.

    • DynaGridStore::STORE_FILTER or 'filter' : if you are storing the detail setting for a grid filter.

    • DynaGridStore::STORE_SORT or 'sort' : if you are storing the detail setting for a grid sort.

  • id: string, the dynagrid element identifier.

  • name: string, the dynagrid detail element to save (typically when you have category set as filter or sort).

  • storage: string, same as DynaGrid storage property. Should be one of the following:

    • 'session' or DynaGrid::TYPE_SESSION: Save the config in a session variable for the current session.

    • 'cookie' or DynaGrid::TYPE_COOKIE: Save the config in a cookie for retrieval. You need to setup the Module::cookieSettings property to control the cookie expiry and other settings.

    • 'db' or DynaGrid::TYPE_DB: Save the config to a database. You need to setup the Module::dbSettings and Module::dbSettingsDtl properties to to setup the database table and attributes for storage.

  • userSpecific: boolean, same as the DynaGrid userSpecific property. Determines whether settings are stored specific to each user. Defaults to true.

  • dbUpdateNameOnly: boolean, whether to update only the name, when editing and saving a filter or sort. This is applicable only when storage is set to Dynagrid::TYPE_DB. Defaults to false. If set to false, it will also overwrite the current filter/sort settings and if set to true, only the filter/sort name will be updated.

  • dtlKey: string, the identifier for the detail configuration (when category is set as filter or sort). If not set, the key will be generated based on the name.

Methods The DynaGridStore object gives access to some important methods:
  • fetch: Fetches configuration from store. You can provide an optional column (string) property (useful when storage is set to db. The column property defaults to the dataAttr setting.

  • save: Saves configuration to the store. You need to provide a config (array) property to save the configuration to the store.

  • delete: Deletes configuration from the store.

Usage

// fetches grid configuration
$store = new DynaGridStore([
    'id' => $this->options['id'], 
    'storage' => 'db',
    'userSpecific' => true,
    'category' => 'grid'
]);
return $store->fetch();

// fetches detail configuration
$store = new DynaGridStore([
    'id' => $id, 
    'storage' => 'db',
    'userSpecific' => true,
    'category' => 'filter',
    'dtlKey' => $dtlId 
]);
return $store->fetch();

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

Note

You can now visit the Krajee Webtips Q & A forum for searching OR asking questions OR helping programmers with answers on these extensions and plugins. For asking a question click here. Select the appropriate question category (i.e. Krajee Plugins) and choose this current page plugin in the question related to field.

The comments and discussion section below are intended for generic discussions or feedback for this plugin. Developers may not be able to search or lookup here specific questions or tips on usage for this plugin.

 
visitors to Krajee Yii2 Demos since 22-May-2017