How to put label of the field before input's div wrapper?

Hi.
I need input field with a prefix like in this Bootstrap5 example.

I try to do it:

                 <?= $form->field($model, 'mpercent', [
                    'template' => "{label}\n{input}\n<span class=\"input-group-text\">%</span>\n{hint}\n{error}",
                    'options' => [ 'class' => 'mb3 input-group']
                 ])->textInput() ?>

It gives this html :

<div class="mb3 input-group field-mainmodel-mpercent">
    <label class="form-label" for="mainmodel-mpercent">My label</label>
    <input type="text" id="mainmodel-mpercent" class="form-control" name="MainModel[mpercent]" value="40">
    <span class="input-group-text">%</span>
</div>

which shows label at the same line with input.

It seems that i need to place label tag before

<div class="mb3 input-group field-mainmodel-mpercent">

How can I do it with $form->field ?

I haven’t tried it but you can probably do it this way:
First, create field as a variable with modified template:

$field = $form->field($model, 'mpercent', [
    'template' => "<span class=\"input-group-text\">%</span>\n{input}\n{hint}\n{error}",
    'options' => [ 'class' => 'mb3 input-group']
]);

Then use it two times:

<?= $field->label(); ?>
<?= $field->textInput(); ?>
1 Like

No, It does not work. This label method is used to tune the field, not for output.

Used next code, and it is ok.

print Html::activeLabel($model, 'mpercent', ['class' => 'form-label']);
2 Likes