Zlatan Omerovic
Zlatan Omerovic

Reputation: 4097

How to add contextual classes in Yii 2 ActiveField / ActiveForm?

In Bootstrap 3 we can add a contextual class to a form-group container which will color that form field container in a specific color, ie. has-error will render it reddish:

<div class="form-group has-error">
    <label for="field">Erroneous label</label>
    <input type="text" class="form-control" placeholder="Erroneous input" id="field" />
    <p class="help-block">Erroneous help-block</p>
</div>

Label, the input's text color and border and final p.help-block will all become red.

In Yii 2 we can use ActiveForm and ActiveField to do the same in one-liner:

<?= $form->field($model, 'field')
    ->textInput(['maxlength' => true, 'placeholder' => 'Erroneous input'])
    ->label('Erroneous label')
    ->hint('Dummy hint') ?>

And it generates roughly the same markup as above, in a form-group container.

I have gone through the docs and didn't find a way to add a has-error class to the form-group container.

Do not work for this scenario.

Upvotes: 0

Views: 468

Answers (1)

Maksym Fedorov
Maksym Fedorov

Reputation: 6456

Yii automatically adds has-error class in case of validation errors. If you want to add any CSS-class to ActiveField container then you can use options property. For example:

<?= $form->field($model, 'field', [
        'options' => [
            'class' => 'form-group has-error',
        ],
    ])
    ->textInput(['maxlength' => true, 'placeholder' => 'Erroneous input'])
    ->label('Erroneous label')
    ->hint('Dummy hint');
?>

Upvotes: 1

Related Questions