zend-frameworkzend-formzend-form-element

Zend Form Element with Javascript - Decorator, View Helper or View Script?


I want to add some javacsript to a Zend_Form_Element_Text .

At first I thought a decorator would be the best way to do it, but since it is just a script (the markup doesn't change) then maybe a view helper is better? or a view script?

It seems like they are all for the same purpose (regarding a form element).

The javascript I want to add is not an event (e.g. change, click, etc.). I can add it easily with headScript() but I want to make it re-usable , that's why I thought about a decorator/view helper. I'm just not clear about the difference between them.

What is the best practice in this case? advantages?

UPDATE: Seems like the best practice is to use view helpers from view scripts , so decorators would be a better fit?

Thanks.


Solution

  • You could create your own decorator by extending Zend_From_Decorator_Abstract and generate your snippet in it's render() method :

    class My_Decorator_FieldInitializer extends Zend_Form_Decorator_Abstract {
        public function render($content){
    
            $separator = $this->getSeparator();
            $element = $this->getElement();
    
            $output = '<script>'.
                 //you write your js snippet here, using 
                 //the data you have in $element if you need 
                 .'</script>';
    
            return $content . $separator . $output;
        }
    }
    

    If you need more details, ask for it in a comment, i'll edit this answer. And I didn't test this code.