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

I want to add javacsript to Zend_Form_Element_Text.

At first I thought that a decorator would be the best way to do this, but since it is just a script (the markup does not change), then maybe the view helper is better? or kind of script?

It seems that they are all for the same purpose (regarding the 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 reusable, so I thought of a decorator / view helper. I just don’t understand the difference between the two.

What is the best practice in this case? advantages?

UPDATE: It seems best to use view helpers from view scripts, so decorators are better suited?

Thanks.

+4
source share
4 answers

You can create your own decorator by expanding Zend_From_Decorator_Abstract and creating your render() fragment in it:

 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 information, ask him in the comment, I will edit this answer. And I have not tested this code.

+2
source

Use the setAttrib function.

eg: -

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

In fact, I do not see where it should be a decorator or view helper or script view.

If I wanted to attach some client-side behavior to the form element, I would probably set the attribute with $elt->setAttrib('class', 'someClass') or $elt->setAttrib('id', 'someId') , some hook that my script can connect to. Then I add listeners / handlers to these target elements.

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

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

The advantage is that it is unobtrusive, so the layout remains clean. I hope javascript is an improvement, not a critical part of the functionality, so it degrades competently.

Perhaps you mean that this javascript segment should be reused for different element identifiers - someClass in this example. In this case, you can simply write a view helper that takes the CSS class name as a parameter.

+2
source

"the markup does not change," Yap,

but I like to add javascript throw ZendForm Element function:

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

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

+1
source

All Articles