yii2 labelEx of ActiveForm

3.7k views Asked by At

in old Yii I was using

    <?php  echo $form->labelEx($model,'text').'<span class="required">* </span>'); ?>

What should I use in yii2 for labeling ?

2

There are 2 answers

8
Ali MasudianPour On BEST ANSWER

The Yii2's way is like below:

<?= $form->field($model, 'fieldName')->label('Label Of FieldName'); ?>

So yours would be something like below:

<?= $form->field($model, 'text')->label('Text'. Html::tag('span', '*',['class'=>'required'])); ?>

Please note that you need to add use yii\helpers\Html; in your View. Otherwise, you need to replace Html:: with yii\helpers\Html::.


Update

For those who suffer from required css class added automatically to parent DIV of a form field:

You can remove it like below:

$form = ActiveForm::begin(['requiredCssClass' => '' ...

Please note that, this applies to your whole form. So whole form has no required css class. You need to write it for each field by yourself.

1
urmaul On

You can use this in css instead of modifying code.

div.required label:after {
    content: " *";
    color: red;
}

That was discussed here: https://github.com/yiisoft/yii2/issues/2056