Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Render a form

Rendering a form is simple. Most elements use a Zend_View helper to render themselves, and thus need a view object in order to render. Other than that, you have two options: use the form's render() method, or simply echo it.

// Explicitly calling render(), and passing an optional view object:
echo $form->render($view);

// Assuming a view object has been previously set via setView():
echo $form;

By default, Zend_Form and Zend_Form_Element will attempt to use the view object initialized in the ViewRenderer, which means you won't need to set the view manually when using the Zend Framework MVC. To render a form in a view, you simply have to do the following:

<?php echo $this->form ?>

Under the hood, Zend_Form uses "decorators" to perform rendering. These decorators can replace content, append content, or prepend content, and can fully introspect the element passed to them. As a result, you can combine multiple decorators to achieve custom effects. By default, Zend_Form_Element actually combines four decorators to achieve its output; setup looks something like this:

'HtmlTag', array('tag' => 'dd')),
'Label', array('tag' => 'dt')),

(Where <HELPERNAME> is the name of a view helper to use, and varies based on the element.)

The above creates output like the following:

<dt><label for="username" class="required">Username</dt>
    <input type="text" name="username" value="123-abc" />
    <ul class="errors">
        <li>'123-abc' has not only alphabetic and digit characters</li>
        <li>'123-abc' does not match against pattern '/^[a-z]/i'</li>

(Albeit not with the same formatting.)

You can change the decorators used by an element if you wish to have different output; see the section on decorators for more information.

The form itself simply loops through the elements, and dresses them in an HTML <form>. The action and method you provided when setting up the form are provided to the <form> tag, as are any attributes you set via setAttribs() and family.

Elements are looped either in the order in which they were registered, or, if your element contains an order attribute, that order will be used. You can set an element's order using:


Or, when creating an element, by passing it as an option:

->addElement('text''username', array('order' => 10));

Zend Framework