Saturday, June 26, 2010

Tutorial - Table layout with Zend Framework form decorators

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:
    array('HtmlTag', array('tag' => 'table')),
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 :) )
    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.


  1. Excellent post! But as I do to remove the label of the buttons, using this example?

    1. Just use:

      $this->[name of the element]->removeDecorator('Label');

  2. This comment has been removed by the author.

  3. Yep, Zend Decorators can be a pain, so thanks for the easy to read and follow article!

    I've got hundreds of forms in a long-lived app, and I'm migrating from a table format to a new a semantic format. For me, I needed to have the format "plug into" my forms -- not manually call the setElementDecorators() each time.

    If you're in a similar situation, check out:
    Plug-in Custom Zend_Form decorators

    I've documented a tabular layout, a ordered-list based layout from ALA, and both work with Dijit.