How to add span to a label using $form->labelEx fr

2019-03-01 07:01发布

I wish to generate the following markup:

<label>some label here <span>(optional)</span></label>

Is there a way to do this, by using Yii labelEx or just label?

Thanks

标签: yii
4条回答
Rolldiameter
2楼-- · 2019-03-01 07:12

It's simple, make use of the Decorator pattern:

<?php
// components/CustomCHtml.php

class CustomCHtml extends CHtml
{
    public static function activeLabelEx($model,$attribute,$htmlOptions=array())
    {
        if (isset($htmlOptions['optional']) && $htmlOptions['optional']) {
            if (isset($htmlOptions['label']) && $htmlOptions['label']) {
                $htmlOptions['label'] .= $htmlOptions['optional'];
            } else {
                $htmlOptions['label'] = $htmlOptions['optional'];
            }
        }

        return parent::activeLabelEx($model,$attribute,$htmlOptions);
    }
}

use case:

<?php echo CustomCHtml::activeLabelEx($model, 'field', array('optional'=>' <span>(optional)</span>')); ?>
查看更多
家丑人穷心不美
3楼-- · 2019-03-01 07:16

Here is a little hack to make it possible.

<?php 
                $username = $form->field($model, 'username')
                ->input('text', ['class' => 'form-control input-lg'])
                ->label(true, 'username', ['class' => 'fa fa-user signin-form-icon']);

                $username->parts['{label}'] = '<span class="fa fa-user signin-form-icon">dwe</span>';

                echo $username;
            ?>
查看更多
淡お忘
4楼-- · 2019-03-01 07:20

You could use CHtml::$afterRequiredLabel and/or CHtml::$beforeRequiredLabel

$initValue = CHtml::$afterRequiredLabel;
CHtml::$afterRequiredLabel = $initValue.'<span>(optional)</span>';
echo $form->labelEx($model, $fname, array('class' => ''));
echo $form->textField($model, $fname, array('class' => ''));
CHtml::$afterRequiredLabel = $initValue;

This way the label will be applied only on the specified form field. You actually set the initial value of CHtml::$afterRequiredLabel and/or CHtml::$beforeRequiredLabel on a temp variable, you overwrite the value that you need, and then reset it to original value.

查看更多
女痞
5楼-- · 2019-03-01 07:24

If the attribute is required

You can set the CHtml static properties like this

CHtml::$beforeRequiredLabel = '';
CHtml::$afterRequiredLabel = '<span>(optional)</span>';

Yii will generate a tag

<label>CHtml::$beforeRequiredLabel.$label.CHtml::$afterRequiredLabel</label>

but the static properties will effect all labels generated by $form->labelEx() (@see CHtml::activeLabelEx())

if you don't need, you must set the static properties to default

If the attribute is not required

you can set the htmlOptions

$form->labelEx($model, $attribute, array('label' => 'your label'))
查看更多
登录 后发表回答