4

I have a Zend application with a Zend_Form, which should use the HTML5 placeholder attribute instead of labels, like done here.

class Application_Form_Usereditprofile extends Zend_Form
{
     public function init()
     {
         [...]
         $this->addElement('text', 'FirstName', array(
            'filters'    => [...],
            'validators' => [...],
            'placeholder'=> 'user_editprofile_firstname', // string I want to translate
         ));
         [...]
     }
}

I initialized Zend_Translate so it should translate my forms by default. This works fine with labels. However, the placeholder gets used as it is, without being translated.

How can I translate the placeholder strings?

Community
  • 1
  • 1
danijar
  • 32,406
  • 45
  • 166
  • 297

3 Answers3

3

You can access the the translate helper like this

'placeholder'=> $this->getView()->translate('user_editprofile_firstname),

btw. the plceholder attribute is not a substitution for the label.

From the spec:

The placeholder attribute should not be used as an alternative to a label.

Jona
  • 2,087
  • 15
  • 24
  • Thanks that works! And placeholder instead of label is ok for me. I dont support outdated browsers. - I had waited for ages for this attribute, and now I'm not allowed to use??? – danijar Dec 03 '11 at 19:25
  • Keep in mind that this will translate the 'placeholder' atrribute as is, future calls to setTranslator and/or translator changes will not affect the outcome. This might be considered breaking the abstraction of from the Zend\Form root. – Denis 'Alpheus' Cahuk Mar 08 '12 at 15:09
2

Here is my final solution. It translates all placeholders. Thanks to Jona for the answer.

foreach($this->getElements() as $key => $element)
{
    $placeholder = $element->getAttrib('placeholder');
    if(isset($placeholder))
    {
        $this->$key->setAttrib('placeholder',$this->getView()->translate($placeholder));
    }
}

That's it!

danijar
  • 32,406
  • 45
  • 166
  • 297
0

Actually I like to have things automated, so I've simply made new My_Form class extending Zend_Form and replaced render method to handle things:

public function render(Zend_View_Interface $view = null)
{
        /**
         * Getting elements.
         */
        $elements = $this->getElements();

        foreach ($elements as $eachElement) {

            /**
             * Auto placeholder translation
             */
            if($eachElement->getAttrib('placeholder') !== NULL && $eachElement->getTranslator() !== NULL ) {
                $placeholderText = $eachElement->getAttrib('placeholder');
                $textTrans =  $eachElement->getTranslator()->translate( $placeholderText);
                $eachElement->setAttrib('placeholder', $textTrans);
            }

        }

    /**
     * Rendering.
     */

    return parent::render($view);
}
Ivan
  • 315
  • 1
  • 3
  • 16