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

The enhanced ActiveForm widget and ActiveField component allows you to control specific Bootstrap library features for Horizontal Forms, Input Groups, and includes more customized inputs.

Important

This widget can be also installed in isolation outside this bundle if needed. In addition to using via \kartik\widgets namespace, this widget can be also installed from the yii2-widget-activeform repository and can also be accessed via \kartik\form\ActiveForm or \kartik\form\ActiveField namespaces.

Pre-Requisites

The kartik\form\ActiveForm widget requires the extended kartik\form\ActiveField component to provide all functionality. Ensure, this pre-requisite is complied with in your widget calls. Any customization should be done by extending these kartik\form\ActiveForm or kartik\form\ActiveField classes.

For explanation on using complex form layouts (e.g. inline form fields with bootstrap horizontal form), you can refer this web-tip.

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)

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

  • To use with bootstrap 3 library - you can set ActiveForm::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 ActiveForm::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 ActiveForm::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 ActiveForm::bsVersion property is set, in addition to Yii::$app->params['bsVersion'], the extension level setting (ActiveForm::bsVersion property) will override the Yii::$app->params['bsVersion']. If ActiveForm::bsVersion property is not set, and Yii::$app->params['bsVersion'] is also not set, ActiveForm::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-widget-activeform 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-widget-activeform via composer package manager. Either run:

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

or add:

"kartik-v/yii2-widget-activeform": "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.

Note

You cannot typically configure the template property through the fieldConfig property nor the active field's template property for this widget when using different orientation other than vertical. The formConfig property allows you to overcome this, by adding ability to control display of labels and validation errors, and controlling input offsets for horizontal forms.

All settings and properties for \yii\widgets\ActiveForm can be used in this widget. In addition the additional properties available with \kartik\form\ActiveForm are:

  • 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-',
       ],
    ];
    
  • type: string, form orientation type as supported for Bootstrap library styling. Must be one of the following values:

    • 'vertical' or ActiveForm::TYPE_VERTICAL

    • 'horizontal' or ActiveForm::TYPE_HORIZONTAL

    • 'inline' or ActiveForm::TYPE_INLINE

    • 'floating' or ActiveForm::TYPE_FLOATING (for Bootstrap 5.x only)

  • fullSpan: int, the Bootstrap full span grid width. Defaults to 12. You can override for custom grid layouts.

  • formConfig: array, the additional configuration for the form widget. The following properties are supported

    • labelSpan: int, the grid width for the label part when the form type is of ActiveForm::TYPE_HORIZONTAL orientation. Should be a number between 1 and fullSpan. Defaults to 2. This is useful in HORIZONTAL forms for setting the label width and offsetting the input.

    • deviceSize: int, the device size to render the grid columns for. Should be one of the bootstrap size modifiers below. Defaults to ActiveForm::SIZE_MEDIUM.

      • 'xs' or ActiveForm::SIZE_X_SMALL

      • 'sm' or ActiveForm::SIZE_SMALL

      • 'md' or ActiveForm::SIZE_MEDIUM

      • 'lg' or ActiveForm::SIZE_LARGE

      • 'xl' or ActiveForm::SIZE_X_LARGE

      This is useful again in HORIZONTAL forms for setting the device size.
    • showLabels: boolean | string. Whether to show field labels. Should be one of the following values:

      • true: show labels for fields

      • false: hide labels for fields

      • ActiveForm::SCREEN_READER: show in screen reader only (hide from normal display)

      Defaults to true. This is useful in INLINE forms, where it defaults to ActiveForm::SCREEN_READER. The autoPlaceholder property for INLINE forms in fieldConfig is defaulted to true.

    • showErrors: boolean, whether to show yii field validation errors. Defaults to true, except for INLINE forms where it defaults to false.

    • showHints: boolean, whether to show hints for each field. Defaults to true. The hint will be rendered only if a valid hint has been set through the hint() method.

  • staticOnly: boolean | Closure, whether all inputs in form are to be rendered as bootstrap 5 static text inputs. Defaults to false. This property takes precedence over disabled or readonly.

    For advanced configuration (e.g. dynamically setting different flags for different fields), this can be setup as a Closure callback. When setup as a Closure callback, you can receive the model instance and the active field object instance as parameters. For example:

    'staticOnly' => function ($model, $field) {
        return in_array($field->attribute, $model->staticOnlyAttributes());
    }
    
  • disabled: boolean, | Closure, whether all inputs in form are to be disabled. Defaults to false.

    For advanced configuration (e.g. dynamically setting different flags for different fields), this can be setup as a Closure callback. When setup as a Closure callback, you can receive the model instance and the active field object instance as parameters. For example:

    'disabled' => function ($model, $field) {
        return in_array($field->attribute, $model->disabledAttributes());
    }
    
  • readonly: boolean, | Closure, whether all inputs in form are to be readonly. Defaults to false.

    For advanced configuration (e.g. dynamically setting different flags for different fields), this can be setup as a Closure callback. When setup as a Closure callback, you can receive the model instance and the active field object instance as parameters. For example:

    'readonly' => function ($model, $field) {
        return in_array($field->attribute, $model->readonlyAttributes());
    }
    

For example, compare the inline form in the previous section above and the one below.

No validation error messages are shown on the inline-form in the previous section (the default behavior). While in the inline-form below, with showErrors set to true in formConfig, the validation errors are displayed.

TIP To easily display a validation error just click in and out of the username or password fields.

Active Field Configuration

The following properties of the ActiveField will help configure the layout specially in combination with and/or without the settings above:

  • horizontalCssClasses: array, CSS grid classes for horizontal layout. This must be an array with these keys:

    • offset: the offset grid class to append to the wrapper if no label is rendered

    • label: the label grid class

    • wrapper: the wrapper grid class

    • error: the error grid class

    • hint: the hint grid class

    These options are compatible and similar to \yii\bootstrap\ActiveForm and provide a complete flexible container. If labelSpan is set in ActiveForm::formConfig and wrapper is also set, then both css options are concatenated. If wrapper contains a 'col-' class wrapper, it overrides the tag from labelSpan.

  • template: string, inherits and overrides values from parent class. This defaults to {label} {beginWrapper} {input} {hint} {error} {endWrapper}. The following tokens are supported:

    • {beginLabel}: Container begin tag for labels (to be used typically along with {labelTitle} token, when you do not wish to directly use the {label} token).

    • {labelTitle}: Label content without tags (to be used typically when you do not wish to directly use the {label} token).

    • {endLabel}: Container end tag for labels (to be used typically with {labelTitle} token, when you do not wish to directly use the {label} token).

    • {label}: Full label content enclosed within the label tag.

    • {beginWrapper}: Container for input,error and hint start tag. Uses a <div> tag if there is a input wrapper CSS detected, else defaults to empty string.

    • {input}: placeholder for input control

    • {hint}: placeholder for hint/help text including sub container

    • {error}: placeholder for error text including sub container

    • {endWrapper}: end tag for {beginWrapper}. Defaults to </div>, if there is a input wrapper CSS detected, else defaults to empty string.

A few examples of configuring a custom template for your bootstrap horizontal active form could look like:

// with labelSpan and deviceSize
echo $form->->field($model, 'email', ['labelSpan' => 2, 'deviceSize' => ActiveForm::SIZE_SMALL]]);

// using horizontalCssClasses
echo $form->->field($model, 'amount_paid', ['horizontalCssClasses' => ['wrapper' => 'hidden-xs']]);
echo $form->->field($model, 'phone', [
    'horizontalCssClasses' => ['label' => 'col-md-2 col-sm-3 col-xs-12 myRedClass']
]);

// using template 
echo $form->->field($model, 'special', [
    'template' => '{beginLabel}For: {labelTitle}{endLabel}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}'
]);
 

Generates a vertical form orientation. You need to set the type parameter to ActiveForm::TYPE_VERTICAL.

NOTE

This is the default orientation if type is not set.

You can set formConfig additionally as:

  • showLabels: boolean | string. Whether to show field labels. Should be one of the following values:

    • true: show labels for fields

    • false: hide labels for fields

    • ActiveForm::SCREEN_READER: show in screen reader only (hide from normal display)

<?php 
    use kartik\form\ActiveForm; // or kartik\widgets\ActiveForm
    $form = ActiveForm::begin([
        'id' => 'login-form-vertical', 
        'type' => ActiveForm::TYPE_VERTICAL
    ]); 
?>
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>
    <?= $form->field($model, 'rememberMe')->checkbox(['custom' => true]) ?>
    <div class="form-group mb-3">
        <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-secondary btn-default']) ?>
    </div>
<?php ActiveForm::end(); ?>

Generates a horizontal form orientation as set in type. You need to set the type parameter to ActiveForm::TYPE_HORIZONTAL.

NOTE

For horizontal forms, you need to set formConfig appropriately as per your user interface needs.

The available formConfig options are:

  • labelSpan The numeric grid width of the label part (integer between 1 to 12)
  • deviceSize Applicable device size (one of the ActiveForm size constants below). Check the bootstrap grid class prefix for more details.
    • 'xs' or ActiveForm::SIZE_X_SMALL

    • 'sm' or ActiveForm::SIZE_SMALL

    • 'md' or ActiveForm::SIZE_MEDIUM

    • 'lg' or ActiveForm::SIZE_LARGE

    • 'xl' or ActiveForm::SIZE_X_LARGE

The formConfig parameters are used to generate the grid layout with the correct offsets required for the horizontal layout. This is of the form: .col-{deviceSize}-{labelSpan}. For example .col-md-2 will be generated if labelSpan is 2 and deviceSize = ActiveForm::SIZE_MEDIUM.
<?php 
    use kartik\form\ActiveForm; // or kartik\widgets\ActiveForm
    $form = ActiveForm::begin([
        'id' => 'login-form-horizontal', 
        'type' => ActiveForm::TYPE_HORIZONTAL,
        'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]
    ]); 
?>
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>
    <?= $form->field($model, 'rememberMe')->checkbox(['id' => 'remember-me-hor', 'custom' => true]) ?>
    <div class="form-group mb-3 row">
        <div class="col-sm-3"></div>
        <div class="col-sm-9">
            <?= Html::submitButton('Login', ['class' => 'btn btn-primary mr-1']) ?>
            <?= Html::resetButton('Reset', ['class' => 'btn btn-secondary btn-default']) ?>
        </div>
    </div>
<?php ActiveForm::end(); ?>
Generates an inline form orientation. You need to set the type parameter to ActiveForm::TYPE_INLINE.
<?php 
    use kartik\form\ActiveForm; // or kartik\widgets\ActiveForm
    $form = ActiveForm::begin([
        'id' => 'login-form-inline', 
        'type' => ActiveForm::TYPE_INLINE,
        'fieldConfig' => ['options' => ['class' => 'form-group mb-3 mr-2 me-2']] // spacing form field groups
    ]); 
?>
    <?= $form->field(\$model, 'username') ?>
    <?= $form->field(\$model, 'password')->passwordInput() ?>
    <?= $form->field(\$model, 'rememberMe')->checkbox(['custom' => true]) ?>
    <div class="form-group mb-3">
    <?= Html::submitButton('Login', ['class' => 'btn btn-primary mr-1']) ?>
    <?= Html::resetButton('Reset', ['class' => 'btn btn-secondary btn-default']) ?>
    </div>

<?php ActiveForm::end(); ?>
Generates an inline form with ability to display field validation errors. You need to set the type parameter to ActiveForm::TYPE_INLINE and set formConfig['showErrors'] to true. Notice how you can customize styles for inline display using tooltipStyleFeedback and some CSS tweaks on the form and checkbox elements. These flex styling capabilities and tooltipStyleFeedback for errors are available only in Bootstrap 5.x / 4.x releases. For applications on Bootstrap 3.x versions, you need to style it with similar CSS accordingly.
<?php 
    use kartik\form\ActiveForm; // or kartik\widgets\ActiveForm
    $form = ActiveForm::begin([
        'id' => 'login-form-inline', 
        'type' => ActiveForm::TYPE_INLINE,
        'tooltipStyleFeedback' => true, // shows tooltip styled validation error feedback
        'fieldConfig' => ['options' => ['class' => 'form-group mb-3 mr-2 me-2']], // spacing field groups
        'formConfig' => ['showErrors' => true],
        'options' => ['style' => 'align-items: flex-start'] // set style for proper tooltips error display
    ]); 
?>
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>
    <?= $form->field($model, 'rememberMe', ['options' => ['class'=>'form-group mb-3 mt-2 mr-2 me-2']])->checkbox(['custom' => true]) ?>
    <?= Html::submitButton('Login', ['class' => 'btn btn-primary mr-1']) ?>
    <?= Html::resetButton('Reset', ['class' => 'btn btn-secondary btn-default']) ?>
<?php ActiveForm::end(); ?>

Generates a Bootstrap 5.x floating labels form with vertical orientation. Note that this is supported only if your Bootstrap version is v5.x. For other Bootstrap versions setting this property has no impact and the form will be rendered with default vertical orientation. For Bootstrap 5.x environments, to activate this layout, you need to set the type parameter to ActiveForm::TYPE_FLOATING.

<?php 
    use kartik\form\ActiveForm; // or kartik\widgets\ActiveForm
    $form = ActiveForm::begin([
        'id' => 'login-form-vertical', 
        'type' => ActiveForm::TYPE_FLOATING
    ]); 
?>
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>
    <?= $form->field($model, 'rememberMe')->checkbox(['custom' => true]) ?>
    <div class="form-group mb-3">
        <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-secondary btn-default']) ?>
    </div>
<?php ActiveForm::end(); ?>

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