ActiveField Widget ActiveField.php

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

NOTE: This extension 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 enhanced ActiveForm and ActiveField widget allows you to control specific Bootstrap 3 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\widgets\ActiveForm widget requires the extended kartik\widgets\ActiveField widget to provide all functionality. Ensure, this pre-requisite is complied with in your widget calls. Any customization should be done by extending these kartik\widgets\ActiveForm or kartik\widgets\ActiveField classes.

NOTE

No additional client assets or scripts (except a 1KB CSS file) are registered with this extension. So there is virtually no performance overhead due to additional Javascript or Cascading Style Sheets. The widget requires the default bootstrap 3.0 assets that are automatically registered with your Yii 2.0 install.

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

Extend form controls by adding text or buttons before, after, or on both sides of any text-based input. You can configure addons by passing the addon property to your field's inputOptions. You can set the following parameters for the addon property:

  • prepend: array the prepend addon configuration, where you set the following keys:

    • content: string the prepend addon content

    • asButton: boolean whether the addon is a button or button group. Defaults to false.

    • options: array HTML attributes for the prepend addon

  • append: array the append addon configuration, where you set the following keys:

    • content: string the append addon content

    • asButton: boolean whether the addon is a button or button group. Defaults to false.

    • options: array HTML attributes for the append addon

  • groupOptions: array HTML options for the input group

  • contentBefore: string content placed before addon. This is not HTML encoded.

  • contentAfter: string content placed after addon. This is not HTML encoded.

@
Enter email address
echo $form->field($model, 'email', [
    'addon' => ['prepend' => ['content'=>'@']]
]);
.00
echo $form->field($model, 'amount_paid', [
    'addon' => ['append' => ['content'=>'.00']],
]);
echo $form->field($model, 'phone', [
    'addon' => ['prepend' => ['content'=>'<i class="glyphicon glyphicon-phone"></i>']]
]);
echo $form->field($model, 'include_text', [
    'addon' => ['prepend' => ['content'=>'']]
]);
echo $form->field($model, 'username', [
    'addon' => [
        'append' => [
            'content' => Html::button('Go', ['class'=>'btn btn-primary']), 
            'asButton' => true
        ]
    ]
]);
echo $form->field($model, 'username', [
    'addon' => [
        'append' => [
            'content' => \yii\bootstrap\ButtonDropdown::widget([
                'label' => 'Action',
                'dropdown' => [
                    'items' => [
                        ['label' => 'Another action', 'url' => '#'],
                        ['label' => 'Something else', 'url' => '#'],
                        '
  • ', ['label' => 'Separated link', 'url' => '#'], ], ], 'options' => ['class'=>'btn-default'] ]), 'asButton' => true ] ] ]);
    echo $form->field($model, 'username', [
        'addon' => [
            'append' => [
                'content' => 
                    \yii\bootstrap\Button::widget([
                        'label'=>'Car', 
                        'options'=>['class'=>'btn btn-default']
                    ]) . PHP_EOL .
                    \yii\bootstrap\Button::widget([
                        'label'=>'Bus', 
                        'options'=>['class'=>'btn btn-default']
                    ]) . PHP_EOL .
                    \yii\bootstrap\ButtonDropdown::widget([
                        'label' => 'Air',
                        'dropdown' => [
                            'items' => [
                                ['label' => 'Another action', 'url' => '#'],
                                ['label' => 'Something else', 'url' => '#'],
                                '
  • ', ['label' => 'Separated link', 'url' => '#'], ], ], 'options' => ['class'=>'btn-default'] ]), 'asButton' => true ] ] ]);
    echo $form->field($model, 'date_1', [
        'addon' => [
            'prepend' => ['content'=>''],
            'append' => ['content'=>'', 'asButton'=>true]
        ]
    ]);
    $.00
    to
    // Controlling addon HTML options
    echo $form->field($model, 'amount_paid', [
        'addon' => [ 
            'prepend' => ['content' => '$', 'options'=>['class'=>'alert-success']],
            'append' => ['content' => '.00', 'options'=>['style' => 'font-family: Monaco, Consolas, monospace;']],
        ]
    ]);
    
    // Displaying a LARGE input
    echo $form->field($model, 'date_3', [
        'addon' => [
            'append' => ['content' => 'to'],
            'groupOptions' => ['class'=>'input-group-lg'],
            'contentAfter' => ''
        ]
    ]);

    Feedback icons can be embedded in text input controls as described in bootstrap optional icons section in form input styling. The following properties are available within ActiveField for one to configure feedback icons.

    • feedbackIcon: array, the configuration for the feedback icon (applicable for bootstrap text inputs). This must be setup as an array containing the following keys:

      • type: string, the icon type to use. Should be one of raw or icon. Defaults to icon, where the default, error and success settings will be treated as an icon CSS suffix name. If set to raw, they will be treated as a raw content markup.

      • prefix: string, the icon CSS class prefix to use if type is icon. Defaults to glyphicon glyphicon-.

      • default: string, the icon (CSS class suffix name or raw markup) to show by default. If not set will not be shown.

      • error: string, the icon (CSS class suffix name or raw markup) to use when input has an error validation. If not set will not be shown.

      • success: string, the icon (CSS class suffix name or raw markup) to use when input has a success validation. If not set will not be shown.

      • defaultOptions: array, the HTML attributes to apply for default icon. The special attribute description can be set to describe this feedback as an aria attribute for accessibility. Defaults to (default).

      • errorOptions: array, the HTML attributes to apply for error icon. The special attribute description can be set to describe this feedback as an aria attribute for accessibility. Defaults to (error).

      • successOptions: array, the HTML attributes to apply for success icon. The special attribute description can be set to describe this feedback as an aria attribute for accessibility. Defaults to (success).

    (default)
    Just a basic feedback icon with no icons for success or error states. Clicking form reset will reset input back to default state.

    (default)(success)(error)
    Multiple feedback icons for different states and setting html attributes for default icon. Try setting a value or clearing a set value to see success or error states.

    (default)(success)(error)
    Using different icon prefixes. Example of using the font awesome icon framework (you must have the font awesome css loaded on your page).

    (default)(success)(error)
    Implementing feedback for input widgets instead of text inputs. Note that the input widget must finally render a bootstrap styled text input (with a CSS class of form-control) for this to work.
    use kartik\widgets\ActiveForm;
    $form = ActiveForm::begin();
    
    // basic feedback icon 
    echo $form->field($model, 'phone_1', [
        'feedbackIcon' => ['default' => 'phone']
    ])->textInput(['placeholder'=>'Enter phone number...']);
    
    // multiple feedback icons
    echo $form->field($model, 'email_2', [
        'feedbackIcon' => [
            'default' => 'envelope',
            'success' => 'ok',
            'error' => 'exclamation-sign',
            'defaultOptions' => ['class'=>'text-primary']
        ]
    ])->textInput(['placeholder'=>'Enter a valid email address...']);
    
    // different icon prefixes
    echo $form->field($model, 'user_2', [
        'feedbackIcon' => [
            'prefix' => 'fa fa-',
            'default' => 'user',
            'success' => 'user-plus',
            'error' => 'user-times',
            'defaultOptions' => ['class'=>'text-warning']
        ]
    ])->textInput(['placeholder'=>'Enter username...']);
    
    // feedback for input widgets instead of text inputs
    echo $form->field($model, 'phone_2', [
        'feedbackIcon' => [
            'prefix' => 'fa fa-',
            'default' => 'phone',
            'success' => 'check-circle',
            'error' => 'exclamation-circle',
        ]
    ])->widget('yii\widgets\MaskedInput', [
        'mask' => '999-999-9999'
    ]);
    
    ActiveForm::end();

    These form inputs have been specifically extended for Bootstrap 3.0 and also include the new HTML 5 inputs. The following additional option exists for all active field inputs:

    • contentBeforeInput: string any markup/content to be placed before the rendered input part of the widget

    • contentAfterInput: string any markup/content to be placed after the rendered input part of the widget

    For example:
    echo $form->field($model, 'field', [
        'contentBeforeInput'=>Html::beginTag('div', ['class='col-sm-10']),
        'contentAfterInput'=>Html::endTag('div'),
    ]);
    

    View a complete demo on HTML5 inputs.

    Renders a checkbox input. The following parameters are supported:

    • options: array, the HTML attributes in terms of name-value pairs. The following options are specially handled:

      • uncheck: string, the value associated with the uncheck state of the radio button. If not set, it will take the default value 0. This method will render a hidden input so that if the checkbox is not checked and is submitted, the value of this attribute will still be submitted to the server via the hidden input. If you do not want any hidden input, you should explicitly set this option as null.

      • label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag. If this is coming from end users, you should Html::encode() or encode it to prevent XSS attacks. When this option is specified, the checkbox will be enclosed by a label tag. If you do not want any label, you should explicitly set this option as null.

      • labelOptions: array, the HTML attributes for the label tag. This is only used when the label option is specified.

      The rest of the options will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using Html::encode(). If a value is null, the corresponding attribute will not be rendered.

      If you set a custom id for the input element, you may need to adjust the $selectors accordingly.

    • enclosedByLabel: boolean, whether to enclose the checkbox within the label. If true, the method will still use template to layout the checkbox and the error message except that the checkbox is enclosed by the label tag.

    The checkbox active field includes enhancements over the yii default checkbox and handles automatic offsetting of checkbox inputs for Horizontal Forms. As an example, check the Remember Me input below.

    <?php 
        $form = ActiveForm::begin([
            'id' => 'login-form', 
            '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() ?>
        <div class="form-group">
            <div class="col-sm-offset-3 col-sm-9">
                <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
            </div>
        </div>
    <?php ActiveForm::end(); ?>

    Renders a radio input. The following parameters are supported:

    • options: array, the HTML attributes in terms of name-value pairs. The following options are specially handled:

      • uncheck: string, the value associated with the uncheck state of the radio button. If not set, it will take the default value 0. This method will render a hidden input so that if the radio button is not checked and is submitted, the value of this attribute will still be submitted to the server via the hidden input. If you do not want any hidden input, you should explicitly set this option as null.

      • label: string, a label displayed next to the radio. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag. If this is coming from end users, you should Html::encode() or encode it to prevent XSS attacks. When this option is specified, the radio will be enclosed by a label tag. If you do not want any label, you should explicitly set this option as null.

      • labelOptions: array, the HTML attributes for the label tag. This is only used when the label option is specified.

      The rest of the options will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using Html::encode(). If a value is null, the corresponding attribute will not be rendered.

      If you set a custom id for the input element, you may need to adjust the $selectors accordingly.

    • enclosedByLabel: boolean, whether to enclose the radio within the label. If true, the method will still use template to layout the radio and the error message except that the radio is enclosed by the label tag.

    The radio active field includes enhancements over the yii default radio and handles automatic offsetting of radio inputs for Horizontal Forms. As an example, check the Yes and No inputs below.

    <?php 
        $form = ActiveForm::begin([
            'id' => 'login-form', 
            'type' => ActiveForm::TYPE_HORIZONTAL,
            'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]
        ]); 
    ?>
        <?= $form->field($model, 'username') ?>
        <?= $form->field($model, 'password')->passwordInput() ?>
        <?= $form->field($model, 'yes')->radio() ?>
        <?= $form->field($model, 'no')->radio() ?>
        <div class="form-group">
            <div class="col-sm-offset-3 col-sm-9">
                <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
            </div>
        </div>
    <?php ActiveForm::end(); ?>

    Use this to generate a stacked checkbox list or an inline checkbox list. For an inline checkbox list set the inline option to true.

    Stacked Checkbox List
    Inline Checkbox List
    $form = ActiveForm::begin([
        'id' => 'login-form', 
        'type' => ActiveForm::TYPE_HORIZONTAL,
        'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]
    ]); 
    
    $list = [0 => 'Morning', 1 => 'Noon', 2 => 'Evening'];
    
    /* Display a stacked checkbox list */
    echo $form->field($model, 'contact')->checkboxList($list);
    
    /* Display an inline checkbox list */
    echo $form->field($model, 'contact')->checkboxList($list, ['inline'=>true]);
    
    ActiveForm::end();

    Use this to generate a stacked radio list or an inline radio list. For an inline radio list set the inline option to true.

    Stacked Radio List
    Inline Radio List
    $form = ActiveForm::begin([
        'id' => 'login-form', 
        'type' => ActiveForm::TYPE_HORIZONTAL,
        'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]
    ]); 
    
    $list = [0 => 'Morning', 1 => 'Noon', 2 => 'Evening'];
    
    /* Display a stacked checkbox list */
    echo $form->field($model, 'contact')->checkboxList($list);
    
    /* Display an inline checkbox list */
    echo $form->field($model, 'contact')->checkboxList($list, ['inline'=>true]);
    
    ActiveForm::end();

    Use this when you need to place plain text with a form label within a vertical or horizontal form. As an example, check the Email Address control below for a horizontal form.

    email@example.com
    Enter email address
    ?php 
        $form = ActiveForm::begin([
            'id' => 'login-form', 
            'type' => ActiveForm::TYPE_HORIZONTAL,
            'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]
        ]); 
    ?>
        <?= $form->field($model, 'username') ?>
        <?= $form->field($model, 'email')->staticInput() ?>
    <?php ActiveForm::end(); ?>

    Allows the new HTML 5 inputs to be displayed and offset for horizontal form orientation. The range input (slider control) is handled separately through the rangeInput function.

    Browser Support

    Not all major browsers support all the new HTML 5 input types. However, you can already start using them. If they are not supported, they will behave as regular text fields. For example, if you are currently using the Google Chrome browser you should be able to see the color and date controls in the example below. For more information on HTML 5 inputs click here.

    View a complete demo on HTML5 inputs.

    $form = ActiveForm::begin([
        'id' => 'login-form', 
        'type' => ActiveForm::TYPE_HORIZONTAL,
        'formConfig' => ['labelSpan' => 6, 'deviceSize' => ActiveForm::SIZE_SMALL]
    ]); 
    
    /* Color input - works with Firefox, Google Chrome & Opera*/
    echo $form->field($model, 'color')->input('color');
    
    /* Number input - works with Firefox, Google Chrome, Safari & Opera*/
    $form->field($model, 'rating')->input('number', ['min'=>1, 'max'=>5, 'placeholder' => 'Enter a rating between 1 and 5...']) ?>
    
    /* Email input - works with Google Chrome & Opera*/
    echo $form->field($model, 'email_1')->input('email', ['placeholder'=>'Enter a valid email...'])
    
    /* Date selector input - works with Google Chrome & Opera */
    echo $form->field($model, 'birthday')->input('date');
    
    ActiveForm::end();

    The checkbox button group generates a list of checkbox toggle buttons styled as a bootstrap button group. The configuration of the checkbox group is very similar to an active field checkbox list.

    Simple basic usage

    Change button group size, button styles, and preselect Mon, Wed, & Fri.

    Advanced usage - Disable selected checkboxes (e.g. Sun & Sat)
    use kartik\form\ActiveForm;
    
    $form = ActiveForm::begin(); 
    $data = [0 => 'Sun', 1 => 'Mon', 2 => 'Tue', 3 => 'Wed', 4 => 'Thu', 5 => 'Fri', 6 => 'Sat'];
    
    // Simple basic usage
    echo $form->field($model, 'weekdays1')->checkboxButtonGroup($data);?>
    
    $model->weekdays2 = [1, 3, 5];
    // Change button group size, button styles, and preselect 'Mon', 'Wed', & 'Fri'
    echo $form->field($model, 'weekdays2')->checkboxButtonGroup($data, [
        'class' => 'btn-group-sm',
        'itemOptions' => ['labelOptions' => ['class' => 'btn btn-warning']]
    ]);
    
    // Advanced usage - Disable selected checkboxes (e.g. 'Sun' & 'Sat')
    echo $form->field($model, 'weekdays3')->checkboxButtonGroup($data, ['disabledItems'=>[0, 6]]);
    ActiveForm::end();

    The radio button group generates a list of radio toggle buttons styled as a bootstrap button group. The configuration of the radio group is very similar to an active field radio list.

    Simple basic usage

    Change button group size, button styles, and preselect Mon.

    Advanced usage - Disable selected radios (e.g. Sun & Sat)
    use kartik\form\ActiveForm;
    
    $form = ActiveForm::begin(); 
    $data = [0 => 'Sun', 1 => 'Mon', 2 => 'Tue', 3 => 'Wed', 4 => 'Thu', 5 => 'Fri', 6 => 'Sat'];
    
    // Simple basic usage
    echo $form->field($model, 'weekdays1')->radioButtonGroup($data);?>
    
    $model->weekdays2 = 1;
    // Change button group size, button styles, and preselect 'Mon'
    echo $form->field($model, 'weekdays2')->radioButtonGroup($data, [
        'class' => 'btn-group-sm',
        'itemOptions' => ['labelOptions' => ['class' => 'btn btn-warning']]
    ]);
    
    // Advanced usage - Disable selected radios (e.g. 'Sun' & 'Sat')
    echo $form->field($model, 'weekdays3')->radioButtonGroup($data, ['disabledItems'=>[0, 6]]);
    ActiveForm::end();

    The multi select is special control extending the Yii checkboxList and radioList. It generates a scrolling multi select list box with checkboxes or radio for selection. The list array can be populated just like any Yii dropDownList. The advantage of this multi-select is that it allows the labels to be HTML formatted. For the usage examples in this demo, the following HTML formatted values are used to populate this multi-select list.
    use kartik\helpers\Html;
    $model->icons = [
        'align-left' => Html::icon('align-left') . ' Align Left',
        'align-center' => Html::icon('align-center') . ' Align Center',
        'align-right' => Html::icon('align-right') . ' Align Right',
        'align-justify' => Html::icon('align-justify') . ' Align Justify',
        'arrow-down' => Html::icon('arrow-down') . ' Direction Down',
        'arrow-up' => Html::icon('arrow-up') . ' Direction Up',
        'arrow-left' => Html::icon('arrow-left') . ' Direction Left',
        'arrow-right' => Html::icon('arrow-right') . ' Direction Right',
    ];
    

    Call the multi select like any other dropdown or text control for a vertical form orientation. Note that by default the control displays checkboxes to select values.

    $form = ActiveForm::begin([
        'id' => 'login-form', 
        'type' => ActiveForm::TYPE_VERTICAL
    ]); 
    echo $form->field($model, 'select_data')->multiselect($model->icons);
    ActiveForm::end();

    The multi select control is automatically offset for the horizontal form type. Note that by default the control displays checkboxes to select values.

    $form = ActiveForm::begin([
        'id' => 'login-form', 
        'type' => ActiveForm::TYPE_HORIZONTAL,
        'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]
    ]);
    echo $form->field($model, 'select_data')->multiselect($model->icons);
    ActiveForm::end();

    Change the multi select to show radios instead of checkboxes by setting the selector property.

    $form = ActiveForm::begin([
        'id' => 'login-form'
    ]); 
    echo $form->field($model, 'select_data')->multiselect($model->icons, ['selector'=>'radio']);
    ActiveForm::end();

    By default the control displays a height of 145px. You can override this by setting the height property under the control options. You can also set additional html options by configuring container within the control options array.

    $form = ActiveForm::begin([
        'id' => 'login-form', 
        'type' => ActiveForm::TYPE_VERTICAL
    ]); 
    echo $form->field($model, 'select_data')->multiselect($model->icons, [
        'height' => '225px',
        'container' => ['class' => 'bg-white']
    ]);
    ActiveForm::end();