How do I allow html tags in label for Zend form element using addElement()?

6.8k views Asked by At

I am brand new to Zend and I've been given a project to make adjustments on. I'd like to add html to the labels for my form elements but I can't seem to get it right.

Here's what I have:

$this->addElement('text', 'school_name', array(
    'filters' => array('StringTrim'),
        'validators' => array(
            array('StringLength', false, array(0, 150)),
        ),
    'required' => true,
    'label' => 'Name* :<img src="picture.png">,
    'size' => '90',
));

As is, of course, the <img src="picture.png"> text gets escaped and the whole string is displayed.

I've read that I need to use 'escape' => false in some capacity but I can't figure out where/how to use it in my specific case.

Any help would be great. Thanks!

2

There are 2 answers

4
Michael Osl On BEST ANSWER

After calling addElement fetch the label's decorator and change the escape setting:

$form->getElement('school_name')->getDecorator('label')->setOption('escape', false);

If you use this type of label a lot, you should consider writing a custom decorator.

0
Onshop On

You can also use the disable_html_escape in 'label_options' when adding an element to the form:

$this->add(array(
    ....
    'options' => array(
        'label' => '<span class="required">Name</span>,
        'label_options' => array(
             'disable_html_escape' => true,
         )
     ),
    ...
));

Credit to Théo Bouveret's post 'Button content in ZF2 forms' for the answer.