Builder Details Tabular Form   Tips

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.

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 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\widgets\ActiveForm widgets.
  • One can easily read and manage the tabular input data using the loadMultiple and validateMultiple functions in yii\base\Model.

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;
  1. 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\widgets\ActiveForm and kartik\widgets\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.
  2. 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
        ]
    ]);
    
  3. form ActiveForm, the ActiveForm instance extending from kartik\widgets\ActiveForm. You normally would call it as $form = \kartik\widgets\ActiveForm::begin();. One of form OR formName is mandatory

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

  5. 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\widgets\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.

  6. 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.

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

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

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

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

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

  12. 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'
    ]
    
  13. 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'],
    ]
    
  14. 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\widgets\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'], 
            '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\widgets\ActiveForm and pass it to the TabularForm widget along with the dataProvider.

use kartik\widgets\ActiveForm;
use kartik\builder\TabularForm;
$form = ActiveForm::begin();
echo TabularForm::widget([
    'dataProvider'=>$dataProvider,
    'form'=>$form,
    'attributes'=>$model->formAttribs
]);
// Add other fields if needed or render your submit button
echo '<div class="text-right">' . 
     Html::submitButton('Submit', ['class'=>'btn btn-primary']) .
     '<div>';
ActiveForm::end();
Scenario 1 Output
Showing {begin, number}-{end, number} of {totalCount, number} {totalCount, plural, one{{item}} other{{items}}}.
#IDNamePublish DateColorAuthorSell AmountActions
1
4,000
2
105.5
3
78.5
4
58.5
5
95.5
6
105.5
7
105.5
8
134.99
9
105.5
10
78.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\widgets\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'=>[
        'floatHeader'=>true,
        'panel'=>[
            'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i> Manage Books</h3>',
            'type' => GridView::TYPE_PRIMARY,
            'after'=> Html::a('<i class="glyphicon glyphicon-plus"></i> Add New', '#', ['class'=>'btn btn-success']) . ' ' . 
                    Html::a('<i class="glyphicon glyphicon-remove"></i> Delete', '#', ['class'=>'btn btn-danger']) . ' ' .
                    Html::submitButton('<i class="glyphicon glyphicon-floppy-disk"></i> Save', ['class'=>'btn btn-primary'])
        ]
    ]   
]);
ActiveForm::end();
Scenario 2 Output
Showing {begin, number}-{end, number} of {totalCount, number} {totalCount, plural, one{{item}} other{{items}}}.

Manage Books

#IDNameAuthorBuy AmountSell AmountStatusActions
1
4,000
2
105.5
3
78.5
4
58.5
5
95.5
6
105.5
7
105.5
8
134.99
9
105.5
10
78.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],
        'name'=>['label'=>'Book Name'],
        'publish_date'=>['label'=>'Published On', 'type'=>TabularForm::INPUT_STATIC]
    ],
    
    // configure other gridview settings
    'gridSettings'=>[
        'panel'=>[
            'heading'=>'<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i> Manage Books</h3>',
            'type'=>GridView::TYPE_PRIMARY,
            'before'=>false,
            'footer'=>false,
            'after'=>Html::button('<i class="glyphicon glyphicon-plus"></i> Add New', ['type'=>'button', 'class'=>'btn btn-success kv-batch-create']) . ' ' . 
                    Html::button('<i class="glyphicon glyphicon-remove"></i> Delete', ['type'=>'button', 'class'=>'btn btn-danger kv-batch-delete']) . ' ' .
                    Html::button('<i class="glyphicon glyphicon-floppy-disk"></i> Save', ['type'=>'button', 'class'=>'btn btn-primary kv-batch-save'])
        ]
    ]
]);
echo Html::endForm();
Scenario 3 Output
Showing {begin, number}-{end, number} of {totalCount, number} {totalCount, plural, one{{item}} other{{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'=>'<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i> Manage Books</h3>',
            'type'=>GridView::TYPE_PRIMARY,
            'before'=>false,
            'footer'=>false,
            'after'=>Html::button('<i class="glyphicon glyphicon-plus"></i> Add New', ['type'=>'button', 'class'=>'btn btn-success kv-batch-create']) . ' ' . 
                    Html::button('<i class="glyphicon glyphicon-remove"></i> Delete', ['type'=>'button', 'class'=>'btn btn-danger kv-batch-delete']) . ' ' .
                    Html::button('<i class="glyphicon glyphicon-floppy-disk"></i> Save', ['type'=>'button', 'class'=>'btn btn-primary kv-batch-save'])
        ],
    ]
]);
echo Html::endForm();
Scenario 4 Output
Showing {begin, number}-{end, number} of {totalCount, number} {totalCount, plural, one{{item}} other{{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