31

I have created new Yii2 basic project and want to dig in.

There is a Username field on login page: enter image description here

I want to change label 'Username' to a custom one, e.g. 'My superb label'. I have read the manual: http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html

After investigating a little I've got the next result: enter image description here

I have changed only template and it has changed the layout:

<?= $form->field($model, 'username', [
    "template" => "<label> My superb label </label>\n{input}\n{hint}\n{error}"
])?>

How to change the text of the label in a correct way? What is best practice?

robsch
  • 9,358
  • 9
  • 63
  • 104
Vadym
  • 1,067
  • 1
  • 13
  • 24

5 Answers5

54
<?= $form->field($model, 'username')->textInput()->label('My superb label') ?>

http://www.yiiframework.com/doc-2.0/yii-bootstrap-activefield.html#label()-detail

Mihai P.
  • 9,307
  • 3
  • 38
  • 49
  • Personally I'd consider this the correct answer, because the question does not state that label should be changed in all instances. For example, consider a model where one wishes to alter the label in _form, because a drop-down is being used for a related table value, whilst the remote ID is displayed in other scenarios. – Rich Harding Jun 09 '18 at 11:41
24

there is an another cool way.

<?= $form->field($model, 'username')->textInput(['class'=>'field-class'])->label('Your Label',['class'=>'label-class']) ?>
Tayyab Hussain
  • 1,658
  • 1
  • 18
  • 21
19

Okay, just override attributeLabels in LoginForm.php:

/**
 * Returns the attribute labels.
 *
 * See Model class for more details
 *  
 * @return array attribute labels (name => label).
 */
public function attributeLabels()
{
    return [
        'username' => 'Логин',
        'password' => 'Пароль',
    ];
}
Vadym
  • 1,067
  • 1
  • 13
  • 24
2

You can also add such function to model:

public function attributeLabels()
{
    return [
        'username' => 'My Login',
        'password' => 'My Pasword',
        'rememberMe' => 'Remember Me, please',
    ];
}
Wiktor
  • 21
  • 1
0

just change the lable from modles like this

'symptomsBefore' => Yii::t('app', 'Has The Patient Suffered from the same or similar symptoms before'),
Haroldo Gondim
  • 7,725
  • 9
  • 43
  • 62
  • This could easily be a comment try to give meaningful answer with an explanation to support your answer. Have a look at [this](https://stackoverflow.com/help/how-to-answer) – ibrhm117 Jul 03 '20 at 11:13