How to customize your Zend Form fields to appear in columns

I received a requirement to change the form layout on a web page. I was not using any decorators on the form so the form was coming up in default format generated by Zend Form.

This is the page which displays the form when some one clicks on Edit

Once you click on Edit the form appears like so

Zend Form default layout without decorators

I had to show the fields in 4 columns so that the layout remains consistent with what was shown to the member before clicking on the Edit link.

I opened the form file (in application/forms directory) and added the following code to the file at the bottom after all the elements had been added to the form.

$this->addDisplayGroups(array(
			'left_fields' => array(
			'elements' => array($email, $firstname, $lastname, $company, $address1, $address2),
			),
		        'right_fields' => array(
			'elements' => array($city, $state, $postcode, $country, $phonenumber),
			),
			'bottom_field' => array(
			'elements' => array($cancel, $submit),
			)
		));		

$this->setDisplayGroupDecorators(array('Description', 'FormElements', 'Fieldset'));

I used the Zend Form addDisplayGroups method to group the fields in three separate groups (left_fields, right_fields, bottom_field) so that Zend Form generates the HTML fieldset element which encloses the form elements.

After adding the above code and running the script you will find no difference except when you do a View Source of the page you will see that 3 HTML fieldsset elements have been generated. Now you can tweak your CSS to align the form elements as you want.

I added the following code in the CSS file.

form fieldset#fieldset-left_fields, form fieldset#fieldset-right_fields
{
    float: left;
    width: 50%;
    border: none;
}

Now when I ran the script I got the desired results and the form fields were formatted in the layout I wanted.

This is how the page looked after adding the above code.

Zend Form new layout using decorators

Hope the above helped!

Leave a Comment