Forms and encoding

Ok, Zend Framework has lots of components to do almost anything.
One of the coolest is the form component, it reduces the time spent coding a form and it’s validation and you can then reuse the form code wherever you want and it will behave exactly the same.
One thing was annoying me. When in a form element label you use accents the label, once parsed, will display either weird characters or the raw html code.
For example take a look at this code:

$this->addElement('text','email',array(
            'size'=>'50',
            'label'=>'Correo Electrónico*',
            'required'=>true,
            'validators'=>array('NotEmpty','EmailAddress')
            ));

I wanted it to read: Correo Electrónico, but instead of ‘ó´it was displaying a weird character or the raw html code for an accented ‘o’ (ó) so I was wondering how can I solve this. It didn’t take me a lot of time to figure this one out, the solution was simple and elegant. When declaring a form element there is a flag that will handle if the label gets escaped or not.

The only thing I did was to change the element declaration from the former to this:

$this->addElement('text','email',array(
            'size'=>'50',
            'label'=>'Correo Electrónico*',
            'required'=>true,
            'validators'=>array('NotEmpty','EmailAddress'),
            'escape'=>false
            ));

That’s it, it works.
Oh, BTW, I have my encodings set to ‘utf-8’, if you have ‘iso-8859-1’ you may leave your accents without encoding as html.

Tags: ,

Comments are closed.