views:

29

answers:

1

Hello,

I would like to change the default behavior of Zend_Form, so that whenever the submit button is clicked, form submission is prevented and an arbitrary JavaScript function is called. This would be done for all forms on the site, however the actual JS function to call may change from form to form.

What would be the most proper way to do this? Through a custom decorator on the submit element? Could you provide some tips?

Thanks.

+4  A: 

In my opinion, Zend_Form shouldn't need or desire any knowledge of the JavaScript. I would add a class to the form and use that class name as your hook for applying javascript.

Imagine a form:

<form class="validate-me">
  <!-- //elements -->
  <input type="submit">
</form> 

You can then apply your JavaScript to forms with a given class name (pseudo JS, use a library)

var el = document.getElementsByClassName('validate-me')[0];
el.on('submit', function(e){
  //validate the form, stop the event if invalid
});

If you want to add extra markup or attributes instead of this approach then you will certainly need to look at decorators.

David Caunt
+1 for the unobtrusive JS. ;-)
David Weinraub
+1 from me too, I like your approach. Would you suggest to add this class tag using a decorator, and then have different types of decorators for each type of form submission?
Dario
Zend Form already has a decorator (HtmlTag I think) to render its own <form> tag. It will use the class provided if you do this: $form = new Zend_Form(); $form->setClass('validate-me');
David Caunt