In this tutorial I will show you how to make form with table layout using Zend_Form. Zend_Form is part of Zend Framework, MVC framework written in PHP with ambition to be the official PHP framework.
It is old-school to use tables in HTML for non-table content, but sometimes it is useful and easier to me it “table”-way.
Using Zend_Form is simple task and you can add filter and validators really easy. Changing default appearance can be accomplished by using decorator. Here is the code that you have to add to your Zend_Form creation:
$this->setDecorators(array( 'FormElements', array('HtmlTag', array('tag' => 'table')), 'Form' ));
First I add “table” element around form elements (inputs, submits, etc.) with setDecorators method. Output would be something like this:
[form] [table] [form elements] [/table] [/form]
Decorators are applied one-by-one, form elements are rendered first, then they are surrounded by table, and finally form tag is rendered. If you are not familiar with decorator design pattern, please check Decoration Pattern in Wikipedia and Zend Framework documentation.
After I’m done with form itself, I have to add specific decorators to form elements (you know, table row and table cell 🙂 )
$this->setElementDecorators(array( 'ViewHelper', 'Errors', array(array('data' => 'HtmlTag'), array('tag' => 'td')), array('Label', array('tag' => 'td')), array(array('row' => 'HtmlTag'), array('tag' => 'tr')) ));
Output will be:
[tr] [td] [label] [/td] [td] [Form Element] [Errors] [/td] [/tr]
Again decorators are applied one-by-one. You can add specific CSS classes for each element so you can style them.
Decorators are hard to understand but they are powerful feature of Zend_Form.