【问题标题】:How to change label text of the ActiveField?如何更改 ActiveField 的标签文本?
【发布时间】:2015-01-28 22:25:14
【问题描述】:

我创建了新的 Yii2 基础项目,想深入研究。

登录页面上有一个用户名字段:

我想将标签“用户名”更改为自定义标签,例如'我的极品标签'。 我已阅读手册: http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html

经过一番调查,我得到了下一个结果:

我只改变了模板,它改变了布局:

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

如何正确更改标签的文字? 最佳做法是什么?

【问题讨论】:

    标签: yii2 active-form


    【解决方案1】:

    只需从这样的模型中更改标签

    'symptomsBefore' => Yii::t('app', 'Has The Patient Suffered from the same or similar symptoms before'),
    

    【讨论】:

    • 这很容易成为评论,尝试给出有意义的答案并提供解释以支持您的答案。看看this
    【解决方案2】:

    您也可以在模型中添加这样的功能:

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

    【讨论】:

      【解决方案3】:

      还有另一种很酷的方法。

      <?= $form->field($model, 'username')->textInput(['class'=>'field-class'])->label('Your Label',['class'=>'label-class']) ?>
      

      【讨论】:

      • 真的有帮助
      • 你是摇滚明星! attributeLabels 对我来说不是一个选项,因为我在单个模型上有多个路由/模板。
      【解决方案4】:

      好的,只需覆盖 LoginForm.php 中的 attributeLabels:

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

      【讨论】:

        【解决方案5】:
        <?= $form->field($model, 'username')->textInput()->label('My superb label') ?>
        

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

        【讨论】:

        • 我个人认为这是正确的答案,因为该问题并未说明在所有情况下都应更改标签。例如,考虑一个希望更改 _form 中的标签的模型,因为下拉列表用于相关的表值,而远程 ID 显示在其他场景中。
        猜你喜欢
        • 1970-01-01
        • 2011-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-20
        • 2022-01-04
        相关资源
        最近更新 更多