An alternative to using configuration-based forms is to subclass
Zend_Form. This has several benefits:
You can unit test your form easily to ensure validations and rendering perform as expected.
Fine-grained control over individual elements.
Re-use of form objects, and greater portability (no need to track config files).
Implementing custom functionality.
The most typical use case would be to use the
init() method to setup specific form elements and
configuration:
<?php
class My_Form_Login extends Zend_Form
{
public function init()
{
$username = new Zend_Form_Element_Text('username');
$username->class = 'formtext';
$username->setLabel('Username:')
->setDecorators(array(
array('ViewHelper',
array('helper' => 'formText')),
array('Label',
array('class' => 'label'))
));
$password = new Zend_Form_Element_Password('password');
$password->class = 'formtext';
$password->setLabel('Password:')
->setDecorators(array(
array('ViewHelper',
array('helper' => 'formPassword')),
array('Label',
array('class' => 'label'))
));
$submit = new Zend_Form_Element_Submit('login');
$submit->class = 'formsubmit';
$submit->setValue('Login')
->setDecorators(array(
array('ViewHelper',
array('helper' => 'formSubmit'))
));
$this->addElements(array(
$username,
$password,
$submit
));
$this->setDecorators(array(
'FormElements',
'Fieldset',
'Form'
));
}
}
This form can then be instantiated with simply:
<?php
$form = new My_Form_Login();
and all functionality is already setup and ready; no config files needed. (Note that this example is greatly simplified, as it contains no validators or filters for the elements.)
Another common reason for extension is to define a set of
default decorators. You can do this by overriding the
loadDefaultDecorators() method:
<?php
class My_Form_Login extends Zend_Form
{
public function loadDefaultDecorators()
{
$this->setDecorators(array(
'FormElements',
'Fieldset',
'Form'
));
}
}




