Krajee

Builder Details Tabular Form

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

The Tabular Form widget allows you to update information from multiple models (typically used in master-detail forms). The widget provides these features:

  • Supports all input types as mentioned in the Form builder widget
  • The widget works exactly like a Yii GridView with an ActiveDataProvider, but allows you to batch update fields and submit the form.
  • Supports features of the GridView like pagination and sorting.
  • Allows each row selection for selective batch processing.
  • Highlight selected table rows.
  • Allows you to add and configure action buttons for each row.
  • Allows you to add batch action buttons for the grid.
  • Configure your own hints to display below each active field attribute.
  • Various Bootstrap 5.x / 4.x / 3.x styling features are available by default. However, one can easily customize and theme it to one\'s liking using any CSS framework.
  • Advanced table styling, columns, and layout configuration by using the features available in the kartik\builder\GridView and kartik\form\ActiveForm widgets.
  • One can easily read and manage the tabular input data using the loadMultiple and validateMultiple functions in yii\base\Model.

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)

TabularForm 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 TabularForm::bsVersion property to one of the following.

  • To use with bootstrap 3 library - you can set TabularForm::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 TabularForm::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 TabularForm::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 TabularForm::bsVersion property is set, in addition to Yii::$app->params['bsVersion'], the extension level setting (TabularForm::bsVersion property) will override the Yii::$app->params['bsVersion']. If TabularForm::bsVersion property is not set, and Yii::$app->params['bsVersion'] is also not set, TabularForm::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 TabularForm Builder widget is primarily based on yii\grid\GridView. It uses the enhanced \kartik\grid\GridView widget to capture multi-row/tabular input and submit the form in a batch mode. Most of the settings are very similar to the \kartik\grid\GridView widget.

Note

The TabularForm widget depends on and uses the yii2-grid module. Hence, the gridview module needs to be setup in your Yii configuration file. An example is shown below:
'modules' => [
   'gridview' =>  [
        'class' => '\kartik\grid\Module'
    ]
];
The widget specifically allows you to configure the following settings;
  • 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-',
       ],
    ];
    
  • dataProvider BaseDataProvider, the \yii\data\BaseDataProvider instance for the tabular form, which will return a list of models. This is mandatory.

    Important

    With release v1.5.0, the extension supports all data providers extending from \yii\data\BaseDataProvider. However, functionalities available within kartik orm\ActiveForm and kartik orm\ActiveField (e.g. model and client validation, attribute labeling etc.) is only possible, if used with an yii\data\ActiveDataProvider. For other cases, a normal HTML form is rendered instead of the ActiveForm. Check the demos for examples.
  • Note

    The dataProvider must be generated from a Model::find() query, similar to the default ActiveDataProvider generated by Gii. For example:
    $query = Model::find();
    //add your conditions
    $query->andWhere($condition1);
    $dataProvider = new \yii\data\ActiveDataProvider([
        'query' => $query,
        'pagination' => [
            'pagesize' => 10
        ]
    ]);
    
  • form ActiveForm, the ActiveForm instance extending from kartik orm\ActiveForm. You normally would call it as $form = \kartik orm\ActiveForm::begin();. One of form OR formName is mandatory

  • formName string, the form name to be provided if not using with model and ActiveForm. One of form OR formName is mandatory.

  • attributes array, the most important part of your tabular form builder configuration. This is mandatory. The attributes array needs to be setup as $attribute => $setting, where:

    • $attribute string, the attribute name from the model. You can define your own custom (non-model) attribute by assigning $setting['type'] to TabularForm::INPUT_RAW.

    • $setting array, the attribute settings which allows you to setup the following properties:

      • type string, the input type for the attribute. Allows you to configure most inputs, widgets, and raw text. Should be one of the values below:

        • TabularForm::INPUT_TEXT or textInput

        • TabularForm::INPUT_TEXTAREA or textarea

        • TabularForm::INPUT_PASSWORD or passwordInput

        • TabularForm::INPUT_DROPDOWN_LIST or dropDownList

        • TabularForm::INPUT_LIST_BOX or listBox

        • TabularForm::INPUT_CHECKBOX or checkbox

        • TabularForm::INPUT_RADIO or radio

        • TabularForm::INPUT_CHECKBOX_LIST or checkboxList

        • TabularForm::INPUT_RADIO_LIST or radioList

        • TabularForm::INPUT_MULTISELECT or multiselect

        • TabularForm::INPUT_FILE or fileInput

        • TabularForm::INPUT_HTML5 or input

        • TabularForm::INPUT_WIDGET or widget

        • TabularForm::INPUT_STATIC or staticInput * useful for showing a display-only field

        • TabularForm::INPUT_HIDDEN or hiddenInput * useful for rendering hidden input

        • TabularForm::INPUT_HIDDEN_STATIC or hiddenStaticInput * combines a display-only field very similar to INPUT_STATIC along with a HIDDEN input.

        • TabularForm::INPUT_RAW or raw * useful to set your own free text, HTML markup,or use a Closure function to return value

      • visible boolean, whether the attribute is visible. One can use this property to control visibility of attributes conditionally.

      • value string | Closure, the value to be displayed if the type is set to TabularForm::INPUT_RAW. This will display the raw text from value field if it is a string. If this is a Closure, your anonymous function call should be of the type: function ($model, $key, $index, $widget) { }, where $model is the current model, $key is the key associated with the data model$index is the zero based index of the attribute array list, and $widget is the current widget instance.

      • staticValue string | Closure, the value to be displayed if the type is set to Form::INPUT_STATIC. If not set, the value will be automatically generated from the value setting above OR from the value of the model attribute. If this is setup as a Closure, your anonymous function call should be of the type: function ($model, $key, $index, $widget) { }, where $model is the current model, $key is the key associated with the data model$index is the zero based index of the attribute array list, and $widget is the current widget instance.

      • label string | boolean, the custom attribute label. If this is not set, the model attribute label will be automatically used. If you set it to false, it will not be displayed.

      • format string | array, applicable only for TabularForm::INPUT_STATIC type. This controls 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 Yii::$app->formatter.Default format is "raw".

      • hiddenStaticOptions array, applicable only for TabularForm::INPUT_HIDDEN_STATIC type. This will allow you to setup HTML attributes for the static control container. For TabularForm::INPUT_HIDDEN_STATIC type, the options setting will represent the HTML attributes for the hidden input.

      • label string | boolean, the custom attribute label. If this is not set, the model attribute label will be automatically used. If you set it to false, it will not be displayed. Note:, the attribute label will be displayed as a table header.

      • labelOptions array, the HTML attributes for the label. Will be applied only when NOT using with active form and only if label is set

      • prepend string, any markup to prepend before the input. For ActiveForm fields this will be prepended before the field group (including label, input, error, hint blocks).

      • append string, any markup to append before the input. For ActiveForm fields this will be appended after the field group (including label, input, error, hint blocks).

      • container array, HTML attributes for the div container to wrap the field group (including input and label for all forms. This also includes error & hint blocks for active forms). If not set or empty, no container will be wrapped.

      • inputContainer array, HTML attributes for the div container to wrap the input control only. If not set or empty, no container will be wrapped. Will be applied only when NOT using with ActiveForm.

      • fieldConfig array, the additional configuration for the ActiveField. Will use the \kartik orm\ActiveField configuration parameters.

      • hint string, the hint text to be shown below the active field.

      • items array, the list of items if input type is one of the following:

        • TabularForm::INPUT_DROPDOWN_LIST or dropDownList

        • TabularForm::INPUT_LIST_BOX or listBox

        • TabularForm::INPUT_CHECKBOX_LIST or checkboxList

        • TabularForm::INPUT_RADIO_LIST or radioList

        • TabularForm::INPUT_MULTISELECT or multiselect

      • enclosedByLabel boolean, whether the input is to be enclosed by label. Applicable only for TabularForm::INPUT_CHECKBOX or TabularForm::INPUT_RADIO. Defaults to true.

      • html5type string, the type of HTML5 input, if input type is set to TabularForm::INPUT_HTML5.

      • widgetClass string, the classname if input type is TabularForm::INPUT_WIDGET.

      • options array, the additional HTML attributes to be applied to the input. These will take in the widget configuration settings if type is set to TabularForm::INPUT_WIDGET.

      • columnOptions array, the grid column settings/configuration.

  • attributeDefaults array, the default settings that will be applied for all attributes. The array will be configured similar to a single attribute setting value in the $attributes array. One will typically default markup and styling like type, container, prepend, append etc. For example:

    'attributeDefaults' => [
        'type' => Form::INPUT_TEXT,
        'prepend' => 'My custom content',
    ]
    

    Note: The settings at the $attributes level will override these default settings.

  • staticOnly bool, whether the entire form is to be converted to static only (read only) inputs irrespective of the attribute configuration. Defaults to false.

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

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

  • gridClass: string the namespaced GridView class name. Defaults to \kartik\grid\GridView. Any other class set here must extend from \kartik\grid\GridView.

  • gridSettings array, the settings for `\kartik\grid\GridView` widget which will display the tabular form content.

  • serialColumn array, the settings for `\kartik\grid\SerialColumn` widget which will display the SerialColumn content. If set to false will not be displayed. Defaults to:

    [
        'class' = '\kartik\grid\SerialColumn'
    ]
    
  • checkboxColumn array, the settings for `\kartik\grid\CheckboxColumn` widget which will display the CheckboxColumn content. If set to false will not be displayed. Defaults to:

    [
        'class' = '\kartik\grid\CheckboxColumn',
        'contentOptions' => ['class' => 'kv-row-select'],
        'headerOptions' => ['class' => 'kv-all-select'],
    ]
    
  • actionColumn array, the settings for `\kartik\grid\ActionColumn` widget which will display the ActionColumn content. If set to false will not be displayed.Defaults to:

    [
        'class' => '\kartik\grid\ActionColumn',
        'updateOptions' => ['style' => 'display:none;']
        'width' => '60px'
    ]
    

Some scenarios of using the Tabular Form Builder are mentioned below:

Step 1: Setting up model method

Setup your attributes array for the tabular form builder. For example you could create a globally accessible method in your model (or any accessible class). It is assumed that you have setup a dataProvider for returning your list of models just like you do in any GridView widget. Note: The filtering is disabled for the TabularForm widget.

TIP

You can also setup most settings for each attribute (except label and columnOptions) as a Closure callback. Check an example below for how publish_date can have the properties type and options setup as a Closure.

Important

To ensure each record in your tabular data is updated correctly even if they are rearranged and read correctly via loadMultiple from the POST submission you must 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,
]);
use kartik\builder\TabularForm;
use kartik\grid\GridView;
use yii\helpers\ArrayHelper;
public function getFormAttribs() {
    return [
        // primary key column
        'id'=>[ // primary key attribute
            'type'=>TabularForm::INPUT_HIDDEN, 
            'columnOptions'=>['hidden'=>true]
        ], 
        'name'=>['type'=>TabularForm::INPUT_TEXT],
        'publish_date'=>[
            'type' => function($model, $key, $index, $widget) {
                return ($key % 2 === 0) ? TabularForm::INPUT_HIDDEN : TabularForm::INPUT_WIDGET;
            },
            'widgetClass'=>\kartik\widgets\DatePicker::classname(), 
            'options'=> function($model, $key, $index, $widget) {
                return ($key % 2 === 0) ? [] :
                [ 
                    'pluginOptions'=>[
                        'format'=>'yyyy-mm-dd',
                        'todayHighlight'=>true, 
                        'autoclose'=>true
                    ]
                ];
            },
            'columnOptions'=>['width'=>'170px']
        ],
        'color'=>[
            'type'=>TabularForm::INPUT_WIDGET, 
            'widgetClass'=>\kartik\color\ColorInput::classname(), 
            'options'=>[ 
                'showDefaultPalette'=>false,
                'pluginOptions'=>[
                    'preferredFormat'=>'name',
                    'palette'=>[
                        [
                            "white", "black", "grey", "silver", "gold", "brown", 
                        ],
                        [
                            "red", "orange", "yellow", "indigo", "maroon", "pink"
                        ],
                        [
                            "blue", "green", "violet", "cyan", "magenta", "purple", 
                        ],
                    ]
                ]
            ],
            'columnOptions'=>['width'=>'150px'],
        ],
        
        'author_id'=>[
            'type'=>TabularForm::INPUT_DROPDOWN_LIST, 
            'items'=>ArrayHelper::map(Author::find()->orderBy('name')->asArray()->all(), 'id', 'name'),
            'columnOptions'=>['width'=>'185px']
        ],
        /*
        'buy_amount'=>[
            'type'=>TabularForm::INPUT_TEXT, 
            'label'=>'Buy',
            'options'=>['class'=>'form-control text-right text-end'], 
            'columnOptions'=>['hAlign'=>GridView::ALIGN_RIGHT, 'width'=>'90px']
        ],
        */
        'sell_amount'=>[
            'type'=>TabularForm::INPUT_STATIC, 
            'label'=>'Sell',
            'columnOptions'=>['hAlign'=>GridView::ALIGN_RIGHT, 'width'=>'90px']
        ],
    ];
}

Step 2: Rendering the tabular form

Create a form instance using \kartik\form\ActiveForm and pass it to the TabularForm widget along with the dataProvider.

use kartik\form\ActiveForm;
use kartik\builder\TabularForm;
$form = ActiveForm::begin();
echo TabularForm::widget([
    'dataProvider'=>$dataProvider,
    'form'=>$form,
    'attributes'=>$model->formAttribs,
    'gridSettings'=>['condensed'=>true]
]);
// Add other fields if needed or render your submit button
echo '<div class="text-right text-end">' . 
     Html::submitButton('Submit', ['class'=>'btn btn-primary']) .
     '<div>';
ActiveForm::end();
Scenario 1 Output
Showing 1-10 of 20 items.
#IDNamePublish DateColorAuthorSell Amount ($)Actions
1
300
2
155.5
3
98.5
4
98.5
5
85.5
6
105.5
7
125.5
8
154.99
9
125.5
10
98.5

Expand scenario 1 to include the following functionalities:

  • Float the table header to stick to the top while scrolling
  • Action buttons toolbar - new record creation, batch save, and batch delete.
  • Position your action buttons toolbar in footer.
  • Style the grid using Bootstrap panels and formatting features from \kartik\grid\GridView
  • Adjust grid settings for an advanced tabular form setup.
  • Remove color attribute and show status as a \kartik\widgets\SwitchInput
use kartik\form\ActiveForm;
use kartik\builder\TabularForm;
$form = ActiveForm::begin();
$attribs = $model->formAttribs;
unset($attribs['attributes']['color']);
$attribs['attributes']['status'] = [
    'type'=>TabularForm::INPUT_WIDGET, 
    'widgetClass'=>\kartik\widgets\SwitchInput::classname()
];

echo TabularForm::widget([
    'dataProvider'=>$dataProvider,
    'form'=>$form,
    'attributes'=>$attribs,
    'gridSettings'=>[
        'condensed'=>true,
        'floatHeader'=>true,
        'panel'=>[
            'heading' => '<i class="fas fa-book"></i> Manage Books',
            'before' => false,
            'type' => GridView::TYPE_PRIMARY,
            'after'=> Html::a('<i class="fas fa-plus"></i> Add New', '#', ['class'=>'btn btn-success']) . ' ' . 
                    Html::a('<i class="fas fa-times"></i> Delete', '#', ['class'=>'btn btn-danger']) . ' ' .
                    Html::submitButton('<i class="fas fa-save"></i> Save', ['class'=>'btn btn-primary'])
        ]
    ]   
]);
ActiveForm::end();
Scenario 2 Output
Showing 1-10 of 20 items.

Manage Books

#IDNameAuthorBuy Amount ($)Sell Amount ($)StatusActions
1
300
2
155.5
3
98.5
4
98.5
5
85.5
6
105.5
7
125.5
8
154.99
9
125.5
10
98.5
  

In your controller action that processes your form submission for the tabular form

use yii\base\Model;
public function actionBatchUpdate()
{
    $sourceModel = new \namespace\YourGridModel;
    $dataProvider = $sourceModel->search(Yii::$app->request->getQueryParams());
    $models = $dataProvider->getModels();
    if (Model::loadMultiple($models, Yii::$app->request->post()) && Model::validateMultiple($models)) {
        $count = 0;
        foreach ($models as $index => $model) {
            // populate and save records for each model
            if ($model->save()) {
                $count++;
            }
        }
        Yii::$app->session->setFlash('success', "Processed {$count} records successfully.");
        return $this->redirect(['index']); // redirect to your next desired page
    } else {
        return $this->render('update', [
            'model'=>$sourceModel,
            'dataProvider'=>$dataProvider
        ]);
    }
}

This scenario includes building a tabular form from an ArrayDataProvider and without needing a ActiveDataProvider. It does not include functionalities of ActiveForm and generates a HTML form that can be read over POST based on the formName property.

use yii\data\ArrayDataProvider;
$dataProvider = new ArrayDataProvider([
    'allModels'=>[
        ['id'=>1, 'name'=>'Book Number 1', 'publish_date'=>'25-Dec-2014'],
        ['id'=>2, 'name'=>'Book Number 2', 'publish_date'=>'02-Jan-2014'],
        ['id'=>3, 'name'=>'Book Number 3', 'publish_date'=>'11-May-2014'],
        ['id'=>4, 'name'=>'Book Number 4', 'publish_date'=>'16-Apr-2014'],
        ['id'=>5, 'name'=>'Book Number 5', 'publish_date'=>'16-Apr-2014']
    ]
]);
echo Html::beginForm();
echo TabularForm::widget([
    // your data provider
    'dataProvider'=>$dataProvider,

    // formName is mandatory for non active forms
    // you can get all attributes in your controller 
    // using $_POST['kvTabForm']
    'formName'=>'kvTabForm',
    
    // set defaults for rendering your attributes
    'attributeDefaults'=>[
        'type'=>TabularForm::INPUT_TEXT,
    ],
    
    // configure attributes to display
    'attributes'=>[
        'id'=>['label'=>'book_id', 'type'=>TabularForm::INPUT_HIDDEN_STATIC, 'columnOptions' => ['vAlign' => GridView::ALIGN_MIDDLE]],
        'name'=>['label'=>'Book Name'],
        'publish_date'=>['label'=>'Published On', 'type'=>TabularForm::INPUT_STATIC]
    ],
    
    // configure other gridview settings
    'gridSettings'=>[
        'condensed' => true,
        'panel'=>[
            'heading'=>'<i class="fas fa-book"></i> Manage Books',
            'before' => false,
            'type'=>GridView::TYPE_PRIMARY,
            'before'=>false,
            'footer'=>false,
            'after'=>Html::button('<i class="fas fa-plus"></i> Add New', ['type'=>'button', 'class'=>'btn btn-success kv-batch-create']) . ' ' . 
                    Html::button('<i class="fas fa-times"></i> Delete', ['type'=>'button', 'class'=>'btn btn-danger kv-batch-delete']) . ' ' .
                    Html::button('<i class="fas fa-save"></i> Save', ['type'=>'button', 'class'=>'btn btn-primary kv-batch-save'])
        ]
    ]
]);
echo Html::endForm();
Scenario 3 Output
Showing 1-5 of 5 items.

Manage Books

#IDBook NamePublished OnActions
1
1
25-Dec-2014
2
2
02-Jan-2014
3
3
11-May-2014
4
4
16-Apr-2014
5
5
16-Apr-2014
  

This scenario extends scenario 3 with a custom calculated field that can be shown as a RAW Input. It also shows how to generate a static only (read only) tabular form by just toggling the staticOnly flag and setting actionColumn property to false. Note that the entire form is set to readonly irrespective of the input types. If you have a RAW input in your form - you must set the staticValue property so that it can be displayed in staticOnly mode.

use yii\data\ArrayDataProvider;
$dataProvider = new ArrayDataProvider([
    'allModels'=>[
        ['id'=>1, 'name'=>'Book Number 1', 'publish_date'=>'25-Dec-2014'],
        ['id'=>2, 'name'=>'Book Number 2', 'publish_date'=>'02-Jan-2014'],
        ['id'=>3, 'name'=>'Book Number 3', 'publish_date'=>'11-May-2014'],
        ['id'=>4, 'name'=>'Book Number 4', 'publish_date'=>'16-Apr-2014'],
        ['id'=>5, 'name'=>'Book Number 5', 'publish_date'=>'16-Apr-2014']
    ]
]);
echo Html::beginForm();
echo TabularForm::widget([
    // your data provider
    'dataProvider'=>$dataProvider,
    
    // set entire form to static only (read only)
    'staticOnly'=>true,
    'actionColumn'=>false,

    // formName is mandatory for non active forms
    // you can get all attributes in your controller 
    // using $_POST['kvTabForm']
    'formName'=>'kvTabForm',
    
    // set defaults for rendering your attributes
    'attributeDefaults'=>[
        'type'=>TabularForm::INPUT_TEXT,
    ],
    
    // configure attributes to display
    'attributes'=>[
        'id'=>['label'=>'ID', 'type'=>TabularForm::INPUT_HIDDEN_STATIC],
        'name'=>['label'=>'Book Name'],
        'details'=>[
            'type'=>TabularForm::INPUT_RAW, 
            'staticValue' => function($m, $k, $i, $w) { 
                return 'Details for book ' . ($k + 1);
            }, 
            'value' => function($m, $k, $i, $w) { 
                return Html::textInput("details", 'Details for book ' . ($k + 1), ['class'=>'form-control']);
            }
        ],
        'publish_date'=>['label'=>'Published On', 'type'=>TabularForm::INPUT_STATIC],
    ],
    
    // configure other gridview settings
    'gridSettings'=>[
        'panel'=>[
            'heading'=>'<i class="fas fa-book"></i> Manage Books',
            'before' => false,
            'type'=>GridView::TYPE_PRIMARY,
            'before'=>false,
            'footer'=>false,
            'after'=>Html::button('<i class="fas fa-plus"></i> Add New', ['type'=>'button', 'class'=>'btn btn-success kv-batch-create']) . ' ' . 
                    Html::button('<i class="fas fa-times"></i> Delete', ['type'=>'button', 'class'=>'btn btn-danger kv-batch-delete']) . ' ' .
                    Html::button('<i class="fas fa-save"></i> Save', ['type'=>'button', 'class'=>'btn btn-primary kv-batch-save'])
        ],
    ]
]);
echo Html::endForm();
Scenario 4 Output
Showing 1-5 of 5 items.

Manage Books

#IDBook NameDetailsPublished On
1
1
Book Number 1
Details for book 1
25-Dec-2014
2
2
Book Number 2
Details for book 2
02-Jan-2014
3
3
Book Number 3
Details for book 3
11-May-2014
4
4
Book Number 4
Details for book 4
16-Apr-2014
5
5
Book Number 5
Details for book 5
16-Apr-2014
  

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