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

一个人想着一个人 提交于 2019-12-05 15:30:45

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.

Use setAttrib function.

eg:-

$element = new Zend_Form_Element_Text('test');
$element->setAttrib('onclick', 'alert("Test")');

I'm not actually seeing where this needs to be a decorator or a view-helper or a view-script.

If I wanted to attach some client-side behavior to a form element, I'd probably set an attribute with $elt->setAttrib('class', 'someClass') or $elt->setAttrib('id', 'someId'), some hook onto which my script can attach. Then I'd add listeners/handlers to those targeted elements.

For example, for a click handler using jQuery , it would be something like:

(function($){
    $(document).ready(function(){
        $('.someClass').click(function(e){
            // handle the event here
        });
    });
})(jQuery);

The benefit is that it is unobtrusive, so the markup remains clean. Hopefully, the javascript is an enhancement- not a critical part of the functionality - so it degrades gracefully.

Perhaps you mean that this javascript segment itself needs to be reusable across different element identifiers - someClass, in this example. In this case, you could simply write a view-helper that accepts the CSS class name as the parameter.

tasmaniski

"the markup doesn't change", Yap,

but I like to add some javascript function throw ZendForm Element:

$text_f = new Zend_Form_Element_Text("text_id");
$text_f->setAttrib('OnChange', 'someFunction($(this));');

The best way is if you are working with a team, where all of you should use same code standard. For me and my team this is the code above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!