Quantcast
Channel: Franz's Web Blog
Viewing all articles
Browse latest Browse all 26

Escaping Zend_Form Error Element Labels in ZF1

$
0
0
Problem:
You have a form element label with extra characters (e.g. *, ", :, etc...) and you want to escape or remove it in the generated error message.

Example Zend Form Element:

$firstName = new Zend_Form_Element_Text('first_name');
$firstName->class = "size_long";
$firstName->setLabel('* First Name:')
->setRequired(true)
->ddFilters(array('StringTrim', 'StripTags'))
->setDecorators(array(
array('ViewHelper', array('helper' => 'formText')),
array('Label', array('class' => 'label')),
array('HtmlTag', array('tag' => 'div', 'class' => 'el_wrapper')),
));

Notice the setLabel() method string have characters "*" and ":"
These characters will show up in your error UL labels that are generated by Zend_Form_Decorator_FormErrors.

Solution:
In your controller when an error is generated...

// assume $form is an instance of Zend_Form
if (!$form->isValid($_POST)) {
$view = $form->getView();
$escape = function ($string) use ($view) {
$string = htmlspecialchars($string, ENT_COMPAT, $view->getEncoding());
$string = str_replace(array('#', ':', '*'), '', $string);
return trim($string);
};
$view->setEscape($escape);
}

This will override the default "htmlspecialchars" escaping of Zend_Form that is being used in the rendering of form elements.

Viewing all articles
Browse latest Browse all 26

Latest Images

Trending Articles





Latest Images