Adding Custom Decorators to Zend_Form in Zend Framework – Part 1
by Raza on Jun.14, 2010, under Zend Framework
Hello Everyone!
I just started work on my Real Estate Management System (REMS). Its first form is a booking search form for properties available for rent. The form consisted of fields like location, start & end booking dates, no.of bedrooms, price range etc. Typically any element defined inside a Zend_Form class is wrapped like this on a view file:
<dl id="ELEMENTID">ELEMENT LABEL</dl> <dd>ELEMENT</dd>
I wanted to get rid of this default styling, so after reading the documentation i achieved it by writing this code in the init() function of my Zend_Form class after defining all the form elements:
$this->setElementDecorators(array('ViewHelper'));
I also converted my Login Form’s layout to a table-based also. Here is the code for that class:
<?php
class Form_Login extends Zend_Form {
public function init() {
$username = $this->createElement('text','username');
$username->setLabel('Username');
$username->setRequired(true);
$username->setAttrib('size','20');
$this->addElement($username);
$password = $this->createElement('password','password');
$password->setLabel('Password');
$password->setRequired(true);
$password->setAttrib('size','20');
$this->addElement($password);
$submit = $this->createElement('submit','submit',array('label'=>'Login'));
$this->addElement($submit);
// Code for Custom Decorators here ...
$username->setDecorators(array(
'ViewHelper',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' =>'td','class' =>'element')),
array('Label',array('tag'=>'td')),
array(array('row'=>'HtmlTag'), array('tag'=>'tr')),
));
$password->setDecorators(array(
'ViewHelper',
'Errors',
array(array('data'=>'HtmlTag'), array('tag'=>'td', 'class'=>'element')),
array('Label', array('tag'=>'td')),
array(array('row'=>'HtmlTag'), array('tag'=>'tr')),
));
$submit->setDecorators(array(
'ViewHelper',
array(array('data'=>'HtmlTag'),array('tag'=>'td','class'=>'element')),
array('Label',array('tag'=>'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr')),
));
$this->setDecorators(array(
'FormElements',
array('HtmlTag',array('tag'=>'table')),
'Form',
));
}
}
?>
I hope this helps everyone out. Also checkout this great article Decorators with Zend_Form on Zend DEVZONE.







