Alexander James King

19th March 2009

Decorating Zend Forms

I'll post a more detailed, downloadable example when I get chance. Feel free to email me if you've got any questions.

By default, Zend Form outputs as a definition list:

<dl>
    <dt><label for="surname">Surname</label></dt>
    <dd><input type="text" name="surname" id="surname" /></dd>
</dl>

I needed to output each field within a paragraph tag and a fieldset surrounding all fields:

<fieldset>
    <p>
        <label for="surname">Surname</label>
        <input type="text" name="surname" id="surname" />
    </p>
</fieldset>

PHP code:

$form = new Zend_Form();
		
// remove form HtmlTag decorator and add a fieldset tag
$form->removeDecorator('HtmlTag');
$form->addDecorator('HtmlTag', array('tag' => 'fieldset'));

// create the form element (there are various ways of doing this - I use $form->createElement as I was creating
// the form from a database so this section sat within a loop)
$element = $form->createElement('text', 'surname', array('label' => 'Surname'));

// remove dd and dt from forms - wrap them both in a p tag
// no extra tag around the label
$element->removeDecorator('Label');
$element->addDecorator('Label');
			
$element->removeDecorator('HtmlTag');
$element->addDecorator('HtmlTag', array('tag' => 'p'));
$form->addElement($element);

// submit button
$submitButton = $form->createElement('submit', 'submitForm', array('label' => 'Submit Form'));
$submitButton->removeDecorator('Label');
			
// submit button differs from other elements
$submitButton->removeDecorator('DtDdWrapper');
$submitButton->addDecorator('HtmlTag', array('tag' => 'p'));
		
$form->addElement($submitButton);
			
					

<< Return to the blog

© 2009 Alexander James King