Yii2: Add encodeLabel in activeLabel

Created on 25 Jun 2014  路  9Comments  路  Source: yiisoft/yii2

Add encodeLabel in activeLabel, i can not use html tags.

label

https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseHtml.php#L1050

under discussion

Most helpful comment

@tadaszelvys
Thank you so much for your help!
I observed this change, was already previously done so, and did not work.

Now is perfect.

Used:

 $form->field($model, 'termsofuse')->checkbox(['label' => Yii::t('app', 'I understand and agree to the <a href="#termsofuse">Terms of Use</a>.')])->label(false);

Image:
image

All 9 comments

have you read the docs for that method? You can set a label that will not be encoded.

label: this specifies the label to be displayed. Note that this will NOT be [[encode()|encoded]].
If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display
(after encoding).

I read the documentation, so I suggested.
Visually this model:

<?= $form->field($model, 'file_legend', ['labelOptions' => ['encode' => false]])->radioList($file_legend); ?>

It is best to:

<?= $form->field($model, 'file_legend', ['labelOptions' => ['label' => $model->getAttributeLabel('file_legend')]])->radioList($file_legend); ?>

You can use ...->field(...)->label(...).

Another problem with encoding label:

use yii\bootstrap\ActiveForm;
$form = ActiveForm::begin(['id' => 'form-register','layout' => 'horizontal']);
echo $form->field($model, 'termsofuse')->checkbox();
ActiveForm::end();

Result:
capturar

Reason:
https://github.com/yiisoft/yii2/blob/master/extensions/bootstrap/ActiveField.php#L383

Any tips for this problem?

Just had the same problem with checkbox yesterday, here's my solution:

echo $form->field($model, 'attributeName')->checkbox([
    'label' => $model->getAttributeLabel('attributeName')
])

yii2 should stop forcing encode, it should be default where appropriate, but configurable, at the moment its very unintuitive on how to disable(mostly)/enable encoding if needed.

@tadaszelvys
I'm using 'yii\bootstrap\ActiveForm'. The 'yii\widgets\ActiveForm' works.

@newerton
it works with yii\bootstrap\ActiveForm too.

yii\bootstrap\ActiveField::checkbox() calls parent::checkbox($options, false) which in turn checks for label in $options and if label is not set then sets the encoded label, and if label is set in $options then its up to you to encode or not.

heres the code which does that:

...
if (!isset($options['label'])) {
    ...
    $options['label'] = Html::encode($this->model->getAttributeLabel($attribute));
}
...

@tadaszelvys
Thank you so much for your help!
I observed this change, was already previously done so, and did not work.

Now is perfect.

Used:

 $form->field($model, 'termsofuse')->checkbox(['label' => Yii::t('app', 'I understand and agree to the <a href="#termsofuse">Terms of Use</a>.')])->label(false);

Image:
image

Was this page helpful?
0 / 5 - 0 ratings