Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HTML Entities in a Zend Form Select

I am populating a Select form element, and if I try to use HTML Entities in the value, it get's converted, rather than displaying the special character.

This code:

$form->field_name->addMultiOption('value', ' • label');

Renders:

<option value="one">&amp;nbsp;&amp;bull; label</option>

But I want it to be:

<option value="one">&nbsp;&bull; label</option>

How do I use HTML entities here?


Hint?

I dug in the code and found that it's using the escape() function from the Zend View Abstract on the label AND the value. Maybe someone knows how to override/overload this function for a specific form element? I don't want to override that behavior by default.

Function from the Zend_View_Helper_FormSelect class

protected function _build($value, $label, $selected, $disable)
{
    if (is_bool($disable)) {
        $disable = array();
    }

    $opt = '<option'
         . ' value="' . $this->view->escape($value) . '"'
         . ' label="' . $this->view->escape($label) . '"';

    // selected?
    if (in_array((string) $value, $selected)) {
        $opt .= ' selected="selected"';
    }

    // disabled?
    if (in_array($value, $disable)) {
        $opt .= ' disabled="disabled"';
    }

    $opt .= '>' . $this->view->escape($label) . "</option>";

    return $opt;
}

This is the function from the Zend_View_Abstract class:

private $_escape = 'htmlspecialchars';

/* SNIP */

public function escape($var)
{
    if (in_array($this->_escape, array('htmlspecialchars', 'htmlentities'))) {
        return call_user_func($this->_escape, $var, ENT_COMPAT, $this->_encoding);
    }

    return call_user_func($this->_escape, $var);
}
like image 726
Sonny Avatar asked Feb 20 '10 17:02

Sonny


2 Answers

Turns out this isn't as complicated as I was making it.

I changed this:

$form->field_name->addMultiOption('value', '&nbsp;&bull; label');

To this:

$form->field_name->addMultiOption('value',
    html_entity_decode('&nbsp;&bull;', ENT_COMPAT, 'UTF-8') . ' label');
like image 122
Sonny Avatar answered Nov 02 '22 18:11

Sonny


You can try to switch off/clear Zend filters for specific fields when you populate them.

$form->getElement('yourElementName')->clearFilters();
// pupulate the element 

When you clear the Zend filters, you can apply your own, prior populating.

like image 20
Marcin Avatar answered Nov 02 '22 16:11

Marcin