Posted on | April 2, 2012 | 4 Comments
In the world of web development, forms are basis of most of your application. Everything that is displayed comes first from a form. The Zend Framework includes a wonderful form class, Zend_Form, that makes it easy to create elements, and when the form is submitted, to filter and validate the user input. What is not so wonderful, are the default decorators that Zend_Form uses.
Zend Form Decorators
Decorators are used to render the various form objects (such as the elements, display groups, or the form itself). Most are optional, and nearly all of them come with customisable options.
By default the Zend_Form object will render the form with a definition list.
The <dl> tag is used in conjunction with <dt> (defines the item in the list) and <dd> (describes the item in the list).
Likewise, the Zend_Form_Element_* obejcts render with a definition description (dd), and if you use a label, a definition title (dt).
<form enctype="application/x-www-form-urlencoded" action="" method="post"> <dl class="zend_form"> <dt id="username-label"> <label for="username" class="optional">Username</label> </dt> <dd id="username-element"> <input type="text" name="username" id="username" value="" /> </dd> </dl> </form>
Here is the php code for the example above:
<?php $form = new Zend_Form(); $form->addElement( new Zend_Form_Element_Text( 'username', array( 'label' => 'username' ) ) ); echo $form;
To remove the dl, dt and dd tags, we explicitly tell our form to use a different set of decorators:
//render our form elements and the "form" tag $form->setDecorators( array( 'FormElements', 'Form' ) ); //Tell all of our form elements to render only itself and the label $form->setElementDecorators( array( 'ViewHelper', 'Label' ) );
The output this time is a lot cleaner:
<form enctype="application/x-www-form-urlencoded" action="" method="post"> <label for="username" class="optional">Username</label> <input type="text" name="username" id="username" value="" /> </form>
In this post I have shown how to remove the default decorators from your Zend_Form object and elements. This has been a very simple post to show how to achieve something specific. I shall be writing a follow-up on Zend Form Decorators, explaining what they are, the Mandatory Decorators, the Common Decorators, the Common Options and a LOT of examples to demonstrate how flexible and versatile Zend_Form is.
Posted By:Richard Parnaby-King