Adding a un-encoded label to an Active Checkbox

When you generate a checkbox using Yii's standard ActiveField mechanism, the label is derived from the attributesLabels in the model class

echo $form->field($holiday,'flexible', ['options' => [ 'class' => 'form-group']])->checkbox( );

The above statement uses the $holiday which was created in the controller using

$holiday = Holiday::find();
The system will populate the label text from the $article->attributeLabels['flexible'] property and ... here is the crunch ... it will then html encode that string, so you can't include any html in your label.

But say we want to emphasize our label, perhaps something like "My dates are flexible" - you can't do it.

But there must be a way ... 

Yes, there is ... we can override the above action by specifying the label as part of the checkbox method

$form->field($holiday,'flexible', ['options' => [ 'class' => 'form-group']])->checkbox(['label' => 'My dates are <strong>flexible</strong>'])

Here, the added options in the checkbox() method, overrides the previous method and does NOT encode the string.

Or going one step further, I wanted a shorter label for small screens, so using a bit of Bootstrap trickery ...

echo $form->field( $holiday,'flexible', ['options' => [ 'class' => 'form-group' ]])
                            'label' => '<span class="hidden-md hidden-sm hidden-xs">My dates are flexible</span><span class=" hidden-lg">Flexible</span>'

Did you know you can hire me?

I take on projects of all sizes. From Consulting to large Development Projects.

If you're starting a new Yii project and would like some help to get setup and running or you need some help with a particular module or you just need someone to develop the whole dang thing, then just ask ...

Leave a Comment