compared with
Key
This line was removed.
This word was removed. This word was added.
This line was added.

Changes (804)

View Page History
{warning:title=This page is deprecated}
With the stable release of 1.5.0, this page is now deprecated; please see [the official manual|http://framework.zend.com/manual/en/zend.form.html] for full documentation.
{warning}
<ac:macro ac:name="warning"><ac:parameter ac:name="title">This page is deprecated</ac:parameter><ac:rich-text-body>
<p>With the stable release of 1.5.0, this page is now deprecated; please see <a href="http://framework.zend.com/manual/en/zend.form.html">the official manual</a> for full documentation.</p></ac:rich-text-body></ac:macro>

<p>What follows is documentation for Zend_Form; it reproduces the documentation found in the repository in order to allow pre-release testers access to the documentation without needing to build it. It will be updated as the developers have time and as new documentation is written.</p>

h2. General note
<h2>General note</h2>

<p>While Zend_Form is in the incubator, you will need to add the incubator Zend_View_Helper path to your view instance to ensure that all will work correctly. This can be done in your bootstrap:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$view = new Zend_View();
$view->addHelperPath('path/to/incubator/library/Zend/View/Helper');
Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setView($view);
{code}
]]></ac:plain-text-body></ac:macro>

<p>Once this has been done, you should be able to test Zend_Form without issue.</p>

{toc:minLevel=1|maxLevel=2}
<ac:macro ac:name="toc"><ac:parameter ac:name="minLevel">1</ac:parameter><ac:parameter ac:name="maxLevel">2</ac:parameter></ac:macro>

h1. Introduction
<h1>Introduction</h1>
<p>Zend_Form simplifies form creation and handling in your web application. It accomplishes the following goals:</p>
* Element validation
* Element filtering
* Element ordering
* Element and Form rendering
* Element and form grouping
* Element and form-level configuration
<ul>
<li>Element validation</li>
<li>Element filtering</li>
<li>Element ordering</li>
<li>Element and Form rendering</li>
<li>Element and form grouping</li>
<li>Element and form-level configuration<br />
It heavily leverages other Zend Framework components to accomplish its goals, including Zend_Config, Zend_Validate, Zend_Filter, and optionally Zend_View.</li>
</ul>

h1. Quick Start

h2. Create a form object
<h1>Quick Start</h1>

Creating a form object is very simple: simply instantiate Zend_Form:
<h2>Create a form object</h2>

<p>Creating a form object is very simple: simply instantiate Zend_Form:</p>
{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form = new Zend_Form;
{code}
]]></ac:plain-text-body></ac:macro>

<p>For advanced use cases, you may want to create a Zend_Form subclass, but for simple forms, you can create a form programmatically using a Zend_Form object.</p>

<p>If you wish to specify the form action and method (always good ideas), you can do so with the setAction() and setMethod() accessors:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->setAction('/resource/process')
->setMethod('post');
{code}
]]></ac:plain-text-body></ac:macro>

<p>The above code sets the form action to the partial URL "/resource/process" &quot;/resource/process&quot; and the form method to HTTP POST. This will be reflected during final rendering.</p>

<p>You can set additional HTML attributes for the &lt;form&gt; tag using the setAttrib() or setAttribs() methods. For instance, if you wish to set the id, set the "id" property: &quot;id&quot; property:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->setAttrib('id', 'login');
{code}
]]></ac:plain-text-body></ac:macro>

h2. Add elements to the form
<h2>Add elements to the form</h2>

A <p>A form is nothing without its elements. Zend_Form ships with some default elements that render XHTML via Zend_View helpers. These are as follows:</p>
* button
* checkbox
* hidden
* image
* password
* radio
* reset
* select (both regular and multi-select types)
* submit
* text
* textarea
<ul>
<li>button</li>
<li>checkbox</li>
<li>hidden</li>
<li>image</li>
<li>password</li>
<li>radio</li>
<li>reset</li>
<li>select (both regular and multi-select types)</li>
<li>submit</li>
<li>text</li>
<li>textarea<br />
You have two options for adding elements to a form: you can instantiate concrete elements and pass in these objects, or you can pass in simply the element type and have Zend_Form instantiate an object of the correct type for you.</li>
</ul>

As some examples:

<p>As some examples:</p>
{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Instantiating an element and passing to the form object:
$form->addElement(new Zend_Form_Element_Text('username'));
// Passing a form element type to the form object:
$form->addElement('text', 'username');
{code}
]]></ac:plain-text-body></ac:macro>

<p>By default, these do not have any validators or filters. This means you will need to configure your elements with minimally validators, and potentially filters. You can either do this (a) before you pass the element to the form, (b) via configuration options passed in when creating an element via Zend_Form, or (c) by pulling the element from the form object and configuring it after the fact.</p>

<p>Let's first look at creating validators for a concrete element instance. You can either pass in Zend_Validate_* objects, or the name of a validator to utilize:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$username = new Zend_Form_Element_Text('username');

// Passing a validator name:
$username->addValidator('alnum');
{code}
]]></ac:plain-text-body></ac:macro>

<p>When using this second option, if the validator can accept constructor arguments, you can pass those in an array as the third parameter:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Pass a pattern
$username->addValidator('regex', false, array('/^[a-z]/i'));
{code}
]]></ac:plain-text-body></ac:macro>

<p>(The second parameter is used to indicate whether or not failure of this validator should prevent later validators from running; by default, this is false.)</p>

<p>You may also wish to specify an element as required. This can be done using either an accessor or by passing an option when creating the element. In the former case:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Make this element required:
$username->setRequired(true);
{code}
]]></ac:plain-text-body></ac:macro>

<p>Filters are registered in basically the same way as validators. For illustration purposes, let's add a filter to lowercase the final value:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$username->addFilter('StringtoLower');
{code}
]]></ac:plain-text-body></ac:macro>

<p>So, our final element setup might look like this:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$username->addValidator('alnum')
->addValidator('regex', false, array('/^[a-z]/i'))
->setRequired(true)
->addFilters(array('StringToLower'));
{code}
]]></ac:plain-text-body></ac:macro>


<p>Simple as this is, doing this for every single element in a form can be a bit tedious. Let's try option (b) from above. When we create a new element using Zend_Form::addElement() as a factory, we can optionally pass in configuration options. These can include validators and filters to utilize. So, to do all of the above implicitly, try the following:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->addElement('text', 'username', array(
'validators' => array(
'filters' => array('StringToLower'),
));
{code}
]]></ac:plain-text-body></ac:macro>

<p>If you find you are setting up elements using the same options in many locations, you may want to consider creating your own Zend_Form_Element subclass and utilizing that class instead; this will save you typing in the long-run.</p>

h2. Render a form
<h2>Render a form</h2>

<p>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.</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// 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;
{code}
]]></ac:plain-text-body></ac:macro>

<p>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. Rendering a form in a view script is then as simple as:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
<?= $this->form ?>
{code}
]]></ac:plain-text-body></ac:macro>

<p>Under the hood, Zend_Form uses "decorators" &quot;decorators&quot; to perform rendering. These decorators can replace content, append content, or prepend content, and have full introspection to 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:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$element->addDecorators(array(
array('ViewHelper', array('helper' => '<HELPERNAME>')),
array('Label', array('tag' => 'dt')),
));
{code}
]]></ac:plain-text-body></ac:macro>

(where <HELPERNAME> <p>(where &lt;HELPERNAME&gt; is the name of a view helper to use, and varies based on the element.)</p>

The above creates output like the following:
<p>The above creates output like the following:</p>

{code:html}
<ac:macro ac:name="code"><ac:default-parameter>html</ac:default-parameter><ac:plain-text-body><![CDATA[
<dt><label for="username"></dt>
<dd>
</ul>
</dd>
{code}
]]></ac:plain-text-body></ac:macro>

(albeit not with the same formatting.)
<p>(albeit not with the same formatting.)</p>

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

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

<p>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:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$element->setOrder(10);
{code}
]]></ac:plain-text-body></ac:macro>

<p>Or, when creating an element, by passing it as an option:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->addElement('text', 'username', array('order' => 10));
{code}
]]></ac:plain-text-body></ac:macro>

h2. Check if a form is valid
<h2>Check if a form is valid</h2>

<p>After a form is submitted, you will need to check and see if it passes validations. Each element is checked against the data provided; if a key matching the element name is not present, and the item is marked as required, validations are run with a null value.</p>

<p>Where does the data come from? You can use $_POST or $_GET, or any other data source you might have at hand (web service requests, for instance):</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
if ($form->isValid($_POST)) {
// success!
// failure!
}
{code}
]]></ac:plain-text-body></ac:macro>

<p>With AJAX requests, you sometimes can get away with validating single elements, or groups of elements. isValidPartial() will validate a partial form. Unlike isValid(), however, if a particular key is not present, it will not run validations for that particular element:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
if ($form->isValidPartial($_POST)) {
// elements present all passed validations
// one or more elements tested failed validations
}
{code}
]]></ac:plain-text-body></ac:macro>

<p>An additional method, processAjax(), can also be used for validating partial forms. Unlike isValidPartial(), it returns a JSON-formatted string containing error messages on failure.</p>

<p>Assuming your validations have passed, you can now fetch the filtered values:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$values = $form->getValues();
{code}
]]></ac:plain-text-body></ac:macro>

<p>If you need the unfiltered values at any point, use:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$unfiltered = $form->getUnfilteredValues();
{code}
]]></ac:plain-text-body></ac:macro>

h2. Get error status
<h2>Get error status</h2>

<p>So, your form failed validations? In most cases, you can simply render the form again, and errors will be displayed when using the default decorators:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
if (!$form->isValid($_POST)) {
echo $form;
return $this->render('form');
}
{code}
]]></ac:plain-text-body></ac:macro>

<p>If you want to inspect the errors, you have two methods. getErrors() returns an associative array of element names / codes (where codes is an array of error codes). getMessages() returns an associative array of element names / messages (where messages is an associative array of error code / error message pairs). If a given element does not have any errors, it will not be included in the array.</p>

h2. Putting It Together
<h2>Putting It Together</h2>

<p>Let's build a simple login form. It will need elements representing:</p>
* username
* password
* submit
<ul>
<li>username</li>
<li>password</li>
<li>submit<br />
For our purposes, let's assume that a valid username should be alphanumeric characters only, start with a letter, have a minimum length of 6, and maximum length of 20; they will be normalized to lowercase. Passwords must be a minimum of 6 characters. We'll simply toss the submit value when done, so it can remain unvalidated.</li>
</ul>

We'll use the power of Zend_Form's configuration options to build the form:

<p>We'll use the power of Zend_Form's configuration options to build the form:</p>
{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form = new Zend_Form(array(
'action' => '/user/login',
),
));
{code}
]]></ac:plain-text-body></ac:macro>

<p>Next, we'll create a controller for handling this:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
class UserController extends Zend_Controller_Action
{
}
}
{code}
]]></ac:plain-text-body></ac:macro>

<p>And a view script for displaying the form:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
<h2>Please login:</h2>
<?= $this->form ?>
{code}
]]></ac:plain-text-body></ac:macro>

<p>As you'll note from the controller code, there's more work to do: while the submission may be valid, you may still need to do some authentication using Zend_Auth, for instance.</p>

h2. Using a Config Object
<h2>Using a Config Object</h2>

<p>All Zend_Form classes are configurable using Zend_Config; you can either pass a Zend_Config object to the constructor or pass it in via setConfig(). Let's look at how we might create the above form using an INI file. First, let's follow the recommendations, and place our configurations into sections reflecting the release location, and focus on the 'development' section. Next, we'll setup a section for the given controller ('user'), and a key for the form ('login'):</p>

{code:ini}
<ac:macro ac:name="code"><ac:default-parameter>ini</ac:default-parameter><ac:plain-text-body><![CDATA[
[development]
; general form metainformation
; submit element
user.login.elements.submit.type = "submit"
{code}
]]></ac:plain-text-body></ac:macro>

<p>You could then pass this to the form constructor:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form = new Zend_Form($config->user->login);
{code}
]]></ac:plain-text-body></ac:macro>

and the entire form will be defined.
<p>and the entire form will be defined.</p>

h1. Creating Form Elements Using Zend_Form_Element
<h1>Creating Form Elements Using Zend_Form_Element</h1>

A <p>A form is made of elements, which typically correspond to HTML form input. Zend_Form_Element encapsulates single form elements, with the following areas of responsibility:</p>

<ul>
* validation <li>validation (is submitted data valid?)
** capturing of validation error codes and messages
<ul>
<li>capturing of validation error codes and messages</li>
</ul>
</li>
* filtering <li>filtering (how is the element escaped or normalized for output?)</li>
* rendering (how is the element displayed?)
* metadata and attributes (what information further qualifies the element?)
<li>rendering (how is the element displayed?)</li>
<li>metadata and attributes (what information further qualifies the element?)</li>
</ul>

The base class, Zend_Form_Element, has reasonable defaults for many cases, but it is best to extend the class for commonly used special purpose elements.

h2. Plugin Loaders
<p>The base class, Zend_Form_Element, has reasonable defaults for many cases, but it is best to extend the class for commonly used special purpose elements.</p>

Zend_Form_Element makes use of Zend_Loader_PluginLoader to allow developers to specify locations of alternate validators, filters, and decorators. Each has its own plugin loader associated with it, and general accessors are used to retrieve and modify each.
<h2>Plugin Loaders</h2>

The following loader types are used with the various plugin loader methods: 'validate', 'filter', and 'decorator'. The type names are case insensitive.
<p>Zend_Form_Element makes use of Zend_Loader_PluginLoader to allow developers to specify locations of alternate validators, filters, and decorators. Each has its own plugin loader associated with it, and general accessors are used to retrieve and modify each.</p>

The methods used to interact with plugin loaders are as follows:
<p>The following loader types are used with the various plugin loader methods: 'validate', 'filter', and 'decorator'. The type names are case insensitive.</p>

* *setPluginLoader($loader, $type)*: $loader is the plugin loader object itself, while type is one of the types specified above. This sets the plugin loader for the given type to the newly specified loader object.
* *getPluginLoader($type)*: retrieves the plugin loader associated with $type.
* *addPrefixPath($prefix, $path, $type = null)*: adds a prefix/path association to the loader specified by $type. If $type is null, it will attempt to add the path to all loaders, by appending the prefix with each of "_Validate", "_Filter", and "_Decorator"; and appending the path with "Validate/", "Filter/", and "Decorator/". If you have all your extra form element classes under a common hierarchy, this is a convenience method for setting the base prefix for them.
* *addPrefixPaths(array $spec)*: allows you to add many paths at once to one or more plugin loaders. It expects each array item to be an array with the keys 'path', 'prefix', and 'type'.
<p>The methods used to interact with plugin loaders are as follows:</p>

Custom validators, filters, and decorators are an easy way to share functionality between forms and encapsulate custom functionality.
<ul>
<li><strong>setPluginLoader($loader, $type)</strong>: $loader is the plugin loader object itself, while type is one of the types specified above. This sets the plugin loader for the given type to the newly specified loader object.</li>
<li><strong>getPluginLoader($type)</strong>: retrieves the plugin loader associated with $type.</li>
<li><strong>addPrefixPath($prefix, $path, $type = null)</strong>: adds a prefix/path association to the loader specified by $type. If $type is null, it will attempt to add the path to all loaders, by appending the prefix with each of &quot;_Validate&quot;, &quot;_Filter&quot;, and &quot;_Decorator&quot;; and appending the path with &quot;Validate/&quot;, &quot;Filter/&quot;, and &quot;Decorator/&quot;. If you have all your extra form element classes under a common hierarchy, this is a convenience method for setting the base prefix for them.</li>
<li><strong>addPrefixPaths(array $spec)</strong>: allows you to add many paths at once to one or more plugin loaders. It expects each array item to be an array with the keys 'path', 'prefix', and 'type'.</li>
</ul>

h2. Validators

If you subscribe to the security mantra of "filter input, escape output," you'll want to validate ("filter input") your form input. In Zend_Form, each element includes its own validator chain, consisting of Zend_Validate_* validators.
<p>Custom validators, filters, and decorators are an easy way to share functionality between forms and encapsulate custom functionality.</p>

Validators may be added to the chain in two ways:
<h2>Validators</h2>

* passing in a concrete validator instance
* providing a validator name -- either a short name or fully qualified class name
<p>If you subscribe to the security mantra of &quot;filter input, escape output,&quot; you'll want to validate (&quot;filter input&quot;) your form input. In Zend_Form, each element includes its own validator chain, consisting of Zend_Validate_* validators. </p>

Let's see some examples:
<p>Validators may be added to the chain in two ways:</p>

{code:php} <ul>
<li>passing in a concrete validator instance</li>
<li>providing a validator name &ndash; either a short name or fully qualified class name</li>
</ul>


<p>Let's see some examples:</p>

<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Concrete validator instance:
$element->addValidator(new Zend_Validate_Alnum());
$element->addValidator('Alnum');
$element->addValidator('alnum');
{code}
]]></ac:plain-text-body></ac:macro>

<p>Short names are typically the validator name minus the prefix. In the default case, this will mean minus the 'Zend_Validate_' prefix. Additionally, the first letter need not be upper-cased.</p>

{note:title=Using Custom Validator Classes}
<ac:macro ac:name="note"><ac:parameter ac:name="title">Using Custom Validator Classes</ac:parameter><ac:rich-text-body>
<p>If you have your own set of validator classes, you can tell Zend_Form_Element about these using addPrefixPath(). For instance, if you have validators under the 'My_Validator' prefix, you can tell Zend_Form_Element about this as follows:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$element->addPrefixPath('My_Validator', 'My/Validator/', 'validate');
{code}
]]></ac:plain-text-body></ac:macro>

<p>(Recall that the third argument indicates which plugin loader on which to perform the action.)</p></ac:rich-text-body></ac:macro>
{note}

<p>If failing a particular validation should prevent later validators from firing, pass boolean true as the second parameter:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$element->addValidator('alnum', true);
{code}
]]></ac:plain-text-body></ac:macro>

<p>If you are using a string name to add a validator, and the validator class accepts arguments to the constructor, you may pass these to the third parameter of addValidator() as an array:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$element->addValidator('StringLength', false, array(6, 20));
{code}
]]></ac:plain-text-body></ac:macro>

<p>Arguments passed in this way should be in the order in which they are defined in the constructor. The above example will instantiate the Zend_Validate_StringLenth class with its $min and $max parameters:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$validator = new Zend_Validate_StringLength(6, 20);
{code}
]]></ac:plain-text-body></ac:macro>

<p>You can also set many validators at once, using addValidators(). The basic usage is to pass an array of arrays, with each array containing 1 to 3 values, matching the constructor of addValidator():</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$element->addValidators(array(
array('NotEmpty', true),
array('stringLength', false, array(6, 20)),
));
{code}
]]></ac:plain-text-body></ac:macro>

<p>If you want to be more verbose or explicit, you can use the array keys 'validator', 'breakChainOnFailure', and 'options':</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$element->addValidators(array(
array(
'options' => array(6, 20)),
));
{code}
]]></ac:plain-text-body></ac:macro>

<p>This usage is good for illustrating how you could then configure validators in a config file:</p>

{code:ini}
<ac:macro ac:name="code"><ac:default-parameter>ini</ac:default-parameter><ac:plain-text-body><![CDATA[
element.validators.notempty.validator = "NotEmpty"
element.validators.notempty.breakChainOnFailure = true
element.validators.strlen.options.min = 6
element.validators.strlen.options.max = 20
{code}
]]></ac:plain-text-body></ac:macro>

<p>Notice that every item has a key, whether or not it needs one; this is a limitation of using configuration files -- &ndash; but it also helps make explicit what the arguments are for. Just remember that any validator options must be specified in order.</p>

<p>To validate an element, pass the value to validate to isValid():</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
if ($element->isValid($value)) {
// valid
// invalid
}
{code}
]]></ac:plain-text-body></ac:macro>

{note:title=Validation Context}
<ac:macro ac:name="note"><ac:parameter ac:name="title">Validation Context</ac:parameter><ac:rich-text-body>
<p>Zend_Form_Element::isValid() supports an additional argument, $context. Zend_Form::isValid() passes the entire array of data being processed to $context when validating a form, and Zend_Form_Element::isValid(), in turn, passes it to each validator. This means you can write validators that are aware of data passed to other form elements. As an example, consider a standard registration form that has fields for both password and a password confirmation; one validation would be that the two fields match. Such a validator might look like the following:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
class My_Validate_PasswordConfirmation extends Zend_Validate_Abstract
{
}
}
{code}
{note}
]]></ac:plain-text-body></ac:macro></ac:rich-text-body></ac:macro>

<p>Validators are processed in order. Each validator is processed, unless a validator created with a true breakChainOnFailure value fails its validation. Be sure to specify your validators in a reasonable order.</p>

<p>After a failed validation, you can retrieve the error codes and messages from the validator chain:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$errors = $element->getErrors();
$messages = $element->getMessages();
{code}
]]></ac:plain-text-body></ac:macro>

<p>(Note: error messages returned are an associative array of error code / error message pairs.)</p>

<p>One final note: Zend_Form_Element implements Zend_Validate_Interface, meaning an element may also be used as a validator in other, non-form related validation chains.</p>

<p>For more information on validators, see the Zend_Validate documentation.</p>

Methods associated with validation include:
<p>Methods associated with validation include:</p>

* addValidator($nameOrValidator, $breakChainOnFailure = false, array $options = null)
* addValidators(array $validators)
* setValidators(array $validators) (overwrites all validators)
* getValidator($name) (retrieve a validator object by name)
* getValidators() (retrieve all validators)
* removeValidator($name) (remove validator by name)
* clearValidators() (remove all validators)
<ul>
<li>addValidator($nameOrValidator, $breakChainOnFailure = false, array $options = null)</li>
<li>addValidators(array $validators)</li>
<li>setValidators(array $validators) (overwrites all validators)</li>
<li>getValidator($name) (retrieve a validator object by name)</li>
<li>getValidators() (retrieve all validators)</li>
<li>removeValidator($name) (remove validator by name)</li>
<li>clearValidators() (remove all validators)</li>
</ul>

h2. Filters

The second part of the security mantra, "Filter input, escape output," is escaping. In Zend Framework, escaping is done via the various classes in Zend_Filter. Zend_Form_Element has support for filter chains, allowing you to specify multiple, sequential filters to utilize. Filtering happens when you retrieve the element value via getValue():
<h2>Filters</h2>

<p>The second part of the security mantra, &quot;Filter input, escape output,&quot; is escaping. In Zend Framework, escaping is done via the various classes in Zend_Filter. Zend_Form_Element has support for filter chains, allowing you to specify multiple, sequential filters to utilize. Filtering happens when you retrieve the element value via getValue():</p>
{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$filtered = $element->getValue();
{code}
]]></ac:plain-text-body></ac:macro>

<p>Filters may be added to the chain in two ways:</p>

* passing in a concrete filter instance
* providing a filter name -- either a short name or fully qualified class name
<ul>
<li>passing in a concrete filter instance</li>
<li>providing a filter name &ndash; either a short name or fully qualified class name</li>
</ul>

Let's see some examples:

<p>Let's see some examples:</p>
{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Concrete filter instance:
$element->addFilter(new Zend_Filter_Alnum());
$element->addFilter('Alnum');
$element->addFilter('alnum');
{code}
]]></ac:plain-text-body></ac:macro>

<p>Short names are typically the filter name minus the prefix. In the default case, this will mean minus the 'Zend_Filter_' prefix. Additionally, the first letter need not be upper-cased.</p>

{note:title=Using Custom Filter Classes}
<ac:macro ac:name="note"><ac:parameter ac:name="title">Using Custom Filter Classes</ac:parameter><ac:rich-text-body>
<p>If you have your own set of filter classes, you can tell Zend_Form_Element about these using addPrefixPath(). For instance, if you have validators under the 'My_Filter' prefix, you can tell Zend_Form_Element about this as follows:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$element->addPrefixPath('My_Filter', 'My/Filter/', 'filter');
{code}
]]></ac:plain-text-body></ac:macro>

<p>(Recall that the third argument indicates which plugin loader on which to perform the action.)</p></ac:rich-text-body></ac:macro>
{note}

<p>If at any time you need the unfiltered value, use the getUnfilteredValue() method:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$unfiltered = $element->getUnfilteredValue();
{code}
]]></ac:plain-text-body></ac:macro>

<p>For more information on filters, see the Zend_Filter documentation.</p>

Methods associated with filters include:
<p>Methods associated with filters include:</p>

* addFilter($nameOrFilter, array $options = null)
* addFilters(array $filters)
* setFilters(array $filters) (overwrites all filters)
* getFilter($name) (retrieve a filter object by name)
* getFilters() (retrieve all filters)
* removeFilter($name) (remove filter by name)
* clearFilters() (remove all filters)
<ul>
<li>addFilter($nameOrFilter, array $options = null)</li>
<li>addFilters(array $filters)</li>
<li>setFilters(array $filters) (overwrites all filters)</li>
<li>getFilter($name) (retrieve a filter object by name)</li>
<li>getFilters() (retrieve all filters)</li>
<li>removeFilter($name) (remove filter by name)</li>
<li>clearFilters() (remove all filters)</li>
</ul>

h2. Decorators

One particular pain point for many web developers is the creation of the XHTML forms themselves. For each element, the developer needs to create markup for the element itself, typically a label, and, if they're being nice to their users, markup for displaying validation error messages. The more elements on the page, the less trivial this task becomes.
<h2>Decorators</h2>

Zend_Form_Element tries to solve this issue through the use of "decorators". Decorators are simply classes that have access to the element and a method for rendering content. For more information on how decorators work, please see the section on Zend_Form_Decorator.
<p>One particular pain point for many web developers is the creation of the XHTML forms themselves. For each element, the developer needs to create markup for the element itself, typically a label, and, if they're being nice to their users, markup for displaying validation error messages. The more elements on the page, the less trivial this task becomes.</p>

The default decorators used by Zend_Form_Element are:
* *ViewHelper*: specifies a view helper to use to render the element
* *Errors*: appends error messages to the element using Zend_View_Helper_FormErrors. If none are present, nothing is appended.
* *HtmlTag*: wraps the element and errors in an HTML &lt;dd&gt; tag.
* *Label*: prepends a label to the element using Zend_View_Helper_FormLabel, and wraps it in a &lt;dt&gt; tag. If no label is provided, just the definition term tag is rendered.
<p>Zend_Form_Element tries to solve this issue through the use of &quot;decorators&quot;. Decorators are simply classes that have access to the element and a method for rendering content. For more information on how decorators work, please see the section on Zend_Form_Decorator.</p>

Since the order in which decorators are registered matters -- first decorator registered is executed first -- you will need to make sure you register your decorators in an appropriate order, or ensure that you set the placement options in a sane fashion. To give an example, here is the code that registers the default decorators:
<p>The default decorators used by Zend_Form_Element are:</p>
<ul>
<li><strong>ViewHelper</strong>: specifies a view helper to use to render the element</li>
<li><strong>Errors</strong>: appends error messages to the element using Zend_View_Helper_FormErrors. If none are present, nothing is appended.</li>
<li><strong>HtmlTag</strong>: wraps the element and errors in an HTML &lt;dd&gt; tag.</li>
<li><strong>Label</strong>: prepends a label to the element using Zend_View_Helper_FormLabel, and wraps it in a &lt;dt&gt; tag. If no label is provided, just the definition term tag is rendered.</li>
</ul>

{code:php}
<p>Since the order in which decorators are registered matters &ndash; first decorator registered is executed first &ndash; you will need to make sure you register your decorators in an appropriate order, or ensure that you set the placement options in a sane fashion. To give an example, here is the code that registers the default decorators:</p>

<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$this->addDecorators(array(
array('ViewHelper', array('helper' => '<HELPERNAME>')),
array('Label', array('tag' => 'dt')),
));
{code}
]]></ac:plain-text-body></ac:macro>

<p>The initial content is created by the 'ViewHelper' decorator, which creates the form element itself. Next, the 'Errors' decorator fetches error messages from the element, and, if any are present, passes them to the 'FormErrors' view helper to render. The next decorator, 'HtmlTag', wraps the element and errors in an HTML &lt;dd&gt; tag. Finally, the last decorator, 'label', retrieves the element's label and passes it to the 'FormLabel' view helper, wrapping it in an HTML &lt;dt&gt; tag; the value is prepended to the content by default The resulting output looks basically like this:</p>

{code:html}
<ac:macro ac:name="code"><ac:default-parameter>html</ac:default-parameter><ac:plain-text-body><![CDATA[
<dt><label for="foo">Foo</label></dt>
<dd>
</ul>
</dd>
{code}
]]></ac:plain-text-body></ac:macro>

<p>For more information on decorators, read the Zend_Form_Decorator section.</p>

Methods associated with decorators include:
<p>Methods associated with decorators include:</p>

* addDecorator($nameOrDecorator, array $options = null)
* addDecorators(array $decorators)
* setDecorators(array $decorators) (overwrites all decorators)
* getDecorator($name) (retrieve a decorator object by name)
* getDecorators() (retrieve all decorators)
* removeDecorator($name) (remove decorator by name)
* clearDecorators() (remove all decorators)
<ul>
<li>addDecorator($nameOrDecorator, array $options = null)</li>
<li>addDecorators(array $decorators)</li>
<li>setDecorators(array $decorators) (overwrites all decorators)</li>
<li>getDecorator($name) (retrieve a decorator object by name)</li>
<li>getDecorators() (retrieve all decorators)</li>
<li>removeDecorator($name) (remove decorator by name)</li>
<li>clearDecorators() (remove all decorators)</li>
</ul>

h2. Metadata and Attributes

Zend_Form_Element handles a variety of attributes and element metadata. Basic attributes include:
<h2>Metadata and Attributes</h2>

* name: the element name. Uses the setName() and getName() accessors.
* label: the element label. Uses the setLabel() and getLabel() accessors.
* order: the index at which an element should appear in the form. Uses the setOrder() and getOrder() accessors.
* value: the current element value. Uses the setValue() and getValue() accessors
* required: flag indicating whether or not the element is required when performing form validation. Uses the setRequired() and getRequired() accessors
<p>Zend_Form_Element handles a variety of attributes and element metadata. Basic attributes include:</p>

Form elements may require additional metadata. For XHTML form elements, for instance, you may want to specify attributes such as the class or id. To facilitate this are a set of accessors:
<ul>
<li>name: the element name. Uses the setName() and getName() accessors.</li>
<li>label: the element label. Uses the setLabel() and getLabel() accessors.</li>
<li>order: the index at which an element should appear in the form. Uses the setOrder() and getOrder() accessors.</li>
<li>value: the current element value. Uses the setValue() and getValue() accessors</li>
<li>required: flag indicating whether or not the element is required when performing form validation. Uses the setRequired() and getRequired() accessors</li>
</ul>

* setAttrib($name, $value): add an attribute
* addAttribs(array $attribs): add many attributes at once
* setAttribs(array $attribs): like addAttribs(), but overwrites
* getAttrib($name): retrieve a single attribute value
* getAttribs(): retrieve all attributes as key/value pairs
* removeAttrib($name): remove a single attribute
* clearAttribs(): clear all attributes

Most of the time, however, you can simply access them as object properties, as Zend_Form_Element utilizes overloading to facilitate access to them:
<p>Form elements may require additional metadata. For XHTML form elements, for instance, you may want to specify attributes such as the class or id. To facilitate this are a set of accessors:</p>

{code:php} <ul>
<li>setAttrib($name, $value): add an attribute</li>
<li>addAttribs(array $attribs): add many attributes at once</li>
<li>setAttribs(array $attribs): like addAttribs(), but overwrites</li>
<li>getAttrib($name): retrieve a single attribute value</li>
<li>getAttribs(): retrieve all attributes as key/value pairs</li>
<li>removeAttrib($name): remove a single attribute</li>
<li>clearAttribs(): clear all attributes</li>
</ul>


<p>Most of the time, however, you can simply access them as object properties, as Zend_Form_Element utilizes overloading to facilitate access to them:</p>

<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$element->class = 'text; // set 'class' attribute to 'text'
{code}
]]></ac:plain-text-body></ac:macro>

<p>By default, all attributes are passed to the view helper used by the element during rendering, and rendered as HTML attributes of the element tag.</p>

h2. Standard elements
<h2>Standard elements</h2>

<p>Zend_Form ships with concrete classes representing the following XHTML elements:</p>
* Button: Zend_Form_Element_Button
* Checkbox: Zend_Form_Element_Checkbox
* Hidden: Zend_Form_Element_Hidden
* Image: Zend_Form_Element_Image
* Multiselect: Zend_Form_Element_Multiselect
* Password: Zend_Form_Element_Password
* Radio: Zend_Form_Element_Radio
* Reset: Zend_Form_Element_Reset
* Select: Zend_Form_Element_Select
* Submit: Zend_Form_Element_Submit
* Text: Zend_Form_Element_Text
* Textarea: Zend_Form_Element_Textarea
<ul>
<li>Button: Zend_Form_Element_Button</li>
<li>Checkbox: Zend_Form_Element_Checkbox</li>
<li>Hidden: Zend_Form_Element_Hidden</li>
<li>Image: Zend_Form_Element_Image</li>
<li>Multiselect: Zend_Form_Element_Multiselect</li>
<li>Password: Zend_Form_Element_Password</li>
<li>Radio: Zend_Form_Element_Radio</li>
<li>Reset: Zend_Form_Element_Reset</li>
<li>Select: Zend_Form_Element_Select</li>
<li>Submit: Zend_Form_Element_Submit</li>
<li>Text: Zend_Form_Element_Text</li>
<li>Textarea: Zend_Form_Element_Textarea</li>
</ul>

h2. Methods

Zend_Form_Element has many, many methods. What follows is a quick summary of
their signatures, grouped by type:
<h2>Methods</h2>

* *Configuration:*
** setOptions(array $options)
** setConfig(Zend_Config $config)
* *I18N:*
** setTranslator(Zend_Translate_Adapter $translator = null)
** getTranslator()
* *Properties:*
** setName($name)
** getName()
** setValue($value)
** getValue()
** getUnfilteredValue()
** setLabel($label)
** getLabel()
** setOrder($order)
** getOrder()
** setRequired($flag)
** getRequired()
** setDescription($description)
** getDescription()
** getType()
** setAttrib($name, $value)
** setAttribs(array $attribs)
** getAttrib($name)
** getAttribs()
* *Plugin loaders and paths:*
** setPluginLoader(Zend_Loader_PluginLoader_Interface $loader, $type)
** getPluginLoader($type)
** addPrefixPath($prefix, $path, $type = null)
** addPrefixPaths(array $spec)
* *Validation:*
** addValidator($validator, $breakChainOnFailure = false, $options = array())
** addValidators(array $validators)
** setValidators(array $validators)
** getValidator($name)
** getValidators()
** removeValidator($name)
** clearValidators()
** isValid($value, $context = null)
** getErrors()
** getMessages()
* *Filters:*
** addFilter($filter, $options = array())
** addFilters(array $filters)
** setFilters(array $filters)
** getFilter($name)
** getFilters()
** removeFilter($name)
** clearFilters()
* *Rendering:*
** setView(Zend_View_Interface $view = null)
** getView()
** addDecorator($decorator, $options = null)
** addDecorators(array $decorators)
** setDecorators(array $decorators)
** getDecorator($name)
** getDecorators()
** removeDecorator($name)
** clearDecorators()
** render(Zend_View_Interface $view = null)
<p>Zend_Form_Element has many, many methods. What follows is a quick summary of<br />
their signatures, grouped by type:</p>

<ul>
<li><strong>Configuration:</strong>
<ul>
<li>setOptions(array $options)</li>
<li>setConfig(Zend_Config $config)</li>
</ul>
</li>
<li><strong>I18N:</strong>
<ul>
<li>setTranslator(Zend_Translate_Adapter $translator = null)</li>
<li>getTranslator()</li>
</ul>
</li>
<li><strong>Properties:</strong>
<ul>
<li>setName($name)</li>
<li>getName()</li>
<li>setValue($value)</li>
<li>getValue()</li>
<li>getUnfilteredValue()</li>
<li>setLabel($label)</li>
<li>getLabel()</li>
<li>setOrder($order)</li>
<li>getOrder()</li>
<li>setRequired($flag)</li>
<li>getRequired()</li>
<li>setDescription($description)</li>
<li>getDescription()</li>
<li>getType()</li>
<li>setAttrib($name, $value)</li>
<li>setAttribs(array $attribs)</li>
<li>getAttrib($name)</li>
<li>getAttribs()</li>
</ul>
</li>
<li><strong>Plugin loaders and paths:</strong>
<ul>
<li>setPluginLoader(Zend_Loader_PluginLoader_Interface $loader, $type)</li>
<li>getPluginLoader($type)</li>
<li>addPrefixPath($prefix, $path, $type = null)</li>
<li>addPrefixPaths(array $spec)</li>
</ul>
</li>
<li><strong>Validation:</strong>
<ul>
<li>addValidator($validator, $breakChainOnFailure = false, $options = array())</li>
<li>addValidators(array $validators)</li>
<li>setValidators(array $validators)</li>
<li>getValidator($name)</li>
<li>getValidators()</li>
<li>removeValidator($name)</li>
<li>clearValidators()</li>
<li>isValid($value, $context = null)</li>
<li>getErrors()</li>
<li>getMessages()</li>
</ul>
</li>
<li><strong>Filters:</strong>
<ul>
<li>addFilter($filter, $options = array())</li>
<li>addFilters(array $filters)</li>
<li>setFilters(array $filters)</li>
<li>getFilter($name)</li>
<li>getFilters()</li>
<li>removeFilter($name)</li>
<li>clearFilters()</li>
</ul>
</li>
<li><strong>Rendering:</strong>
<ul>
<li>setView(Zend_View_Interface $view = null)</li>
<li>getView()</li>
<li>addDecorator($decorator, $options = null)</li>
<li>addDecorators(array $decorators)</li>
<li>setDecorators(array $decorators)</li>
<li>getDecorator($name)</li>
<li>getDecorators()</li>
<li>removeDecorator($name)</li>
<li>clearDecorators()</li>
<li>render(Zend_View_Interface $view = null)</li>
</ul>
</li>
</ul>

h2. Configuration

Zend_Form_Element's constructor accepts either an array of options or a Zend_Config object containing options, and it can also be configured using either setOptions() or setConfig(). Generally speaking, keys are named as follows:

* If 'set' + key refers to a Zend_Form_Element method, then the value provided will be passed to that method.
* Otherwise, the value will be used to set an attribute.
<h2>Configuration</h2>

Exceptions to the rule include the following:
<p>Zend_Form_Element's constructor accepts either an array of options or a Zend_Config object containing options, and it can also be configured using either setOptions() or setConfig(). Generally speaking, keys are named as follows:</p>

* prefixPath will be passed to addPrefixPaths()
* The following setters cannot be set in this way:
** setAttrib (though setAttribs *will* work)
** setConfig
** setOptions
** setPluginLoader
** setTranslator
** setView
<ul>
<li>If 'set' + key refers to a Zend_Form_Element method, then the value provided will be passed to that method.</li>
<li>Otherwise, the value will be used to set an attribute.</li>
</ul>

As an example, here is a config file that passes configuration for every type of configurable data:

<p>Exceptions to the rule include the following:</p>
{code:ini}
<ul>
<li>prefixPath will be passed to addPrefixPaths()</li>
<li>The following setters cannot be set in this way:
<ul>
<li>setAttrib (though setAttribs <strong>will</strong> work)</li>
<li>setConfig</li>
<li>setOptions</li>
<li>setPluginLoader</li>
<li>setTranslator</li>
<li>setView</li>
</ul>
</li>
</ul>


<p>As an example, here is a config file that passes configuration for every type of configurable data:</p>

<ac:macro ac:name="code"><ac:default-parameter>ini</ac:default-parameter><ac:plain-text-body><![CDATA[
[element]
name = "foo"
decorators.element.options.helper = "FormText"
decorators.label.decorator = "Label"
{code}
]]></ac:plain-text-body></ac:macro>

h2. Custom elements
<h2>Custom elements</h2>

<p>You can create your own custom elements by simply extending the Zend_Form_Element class. Common reasons to do so include:</p>

* Elements that share common validators and/or filters
* Elements that have custom decorator functionality
<ul>
<li>Elements that share common validators and/or filters</li>
<li>Elements that have custom decorator functionality</li>
</ul>

As an example, let's say that all text elements in a form you are creating need to be filtered with StringTrim, validated with a common regular expression, and that you want to use a custom decorator you've created for displaying them, 'My_Decorator_TextItem'. You could define such an element as follows:

<p>As an example, let's say that all text elements in a form you are creating need to be filtered with StringTrim, validated with a common regular expression, and that you want to use a custom decorator you've created for displaying them, 'My_Decorator_TextItem'. You could define such an element as follows:</p>
{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
class My_Element_Text extends Zend_Form_Element
{
}
}
{code}
]]></ac:plain-text-body></ac:macro>

<p>You could then inform your form object about the prefix path for such elements, and start creating elements:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->addPrefixPath('My_Element', 'My/Element/', 'element')
->addElement('foo', 'text');
{code}
]]></ac:plain-text-body></ac:macro>

<p>The 'foo' element will now be of type My_Element_Text, and exhibit the behaviour you've outlined.</p>

<p>There are many ways to customize elements; be sure to read the API documentation of Zend_Form_Element to know all the methods available.</p>

h1. Creating Forms Using Zend_Form
<h1>Creating Forms Using Zend_Form</h1>

<p>The Zend_Form class is used to aggregate form elements, display groups, and subforms. It can then perform the following actions on those items:</p>

* Validation, including retrieving error codes and messages
<ul>
<li>Validation, including retrieving error codes and messages</li>
* Value <li>Value aggregation, including populating items and retrieving both filtered and unfiltered values from all items</li>
* Iteration <li>Iteration over all items, in the order in which they are entered or based on the order hints retrieved from each item</li>
* Rendering <li>Rendering of the entire form, either via a single decorator that peforms custom rendering or by iterating over each item in the form<br />
*<br />
While forms created with Zend_Form may be complex, probably the best use case is for simple forms; it's best use is for Rapid Application Development and prototyping.</li>
* </ul>
While forms created with Zend_Form may be complex, probably the best use case is for simple forms; it's best use is for Rapid Application Development and prototyping.

At its most basic, you simply instantiate a form object:

<p>At its most basic, you simply instantiate a form object:</p>
{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Generic form object:
$form = new Zend_Form();
// Custom form object:
$form = new My_Form()
{code}
]]></ac:plain-text-body></ac:macro>

<p>You can optionally pass in configuration, which will be used to set object state, as well as to potentially create new elements:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Passing in configuration options:
$form = new Zend_Form($config);
{code}
]]></ac:plain-text-body></ac:macro>

<p>Zend_Form is iterable, and will iterate over elements, display groups, and subforms, using the order they were registered and any order index each may have. This is useful in cases where you wish to render the elements manually in the appropriate order.</p>

<p>Zend_Form's magic lies in its ability to serve as a factory for elements and display groups, as well as the ability to render itself through decorators.</p>

h2. Plugin Loaders
<h2>Plugin Loaders</h2>

<p>Zend_Form makes use of Zend_Loader_PluginLoader to allow developers to specify locations of alternate elements and decorators. Each has its own plugin loader associated with it, and general accessors are used to retrieve and modify each.</p>

<p>The following loader types are used with the various plugin loader methods: 'element' and 'decorator'. The type names are case insensitive.</p>

<p>The methods used to interact with plugin loaders are as follows:</p>

<ul>
* setPluginLoader($loader, <li>setPluginLoader($loader, $type): $loader is the plugin loader object itself, while type is one of the types specified above. This sets the plugin loader for the given type to the newly specified loader object.</li>
* getPluginLoader($type): retrieves the plugin loader associated with $type.
<li>getPluginLoader($type): retrieves the plugin loader associated with $type.</li>
* addPrefixPath($prefix, <li>addPrefixPath($prefix, $path, $type = null): adds a prefix/path association to the loader specified by $type. If $type is null, it will attempt to add the path to all loaders, by appending the prefix with each of "_Element" &quot;_Element&quot; and "_Decorator"; &quot;_Decorator&quot;; and appending the path with "Element/" &quot;Element/&quot; and "Decorator/". &quot;Decorator/&quot;. If you have all your extra form element classes under a common hierarchy, this is a convenience method for setting the base prefix for them.</li>
* addPrefixPaths(array <li>addPrefixPaths(array $spec): allows you to add many paths at once to one or more plugin loaders. It expects each array item to be an array with the keys 'path', 'prefix', and 'type'.</li>
</ul>

Custom elements and decorators are an easy way to share functionality between forms and encapsulate custom functionality.

h2. Elements
<p>Custom elements and decorators are an easy way to share functionality between forms and encapsulate custom functionality.</p>

Zend_Form provides several accessors for adding and removing elements from the form. These can take element object instances or serve as factories for instantiating the element objects themselves.
<h2>Elements</h2>

The most basic method for adding an element is addElement(). This method can take either an object of type Zend_Form_Element (or of a class extending Zend_Form_Element), or arguments for building a new element -- including the element type, name, and any configuration options.
<p>Zend_Form provides several accessors for adding and removing elements from the form. These can take element object instances or serve as factories for instantiating the element objects themselves.</p>

As some examples:
<p>The most basic method for adding an element is addElement(). This method can take either an object of type Zend_Form_Element (or of a class extending Zend_Form_Element), or arguments for building a new element &ndash; including the element type, name, and any configuration options.</p>

<p>As some examples:</p>
{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Using an element instance:
$element = new Zend_Form_Element_Text('foo');
// Pass label option to the element:
$form->addElement('text', 'foo', array('label' => 'Foo:'));
{code}
]]></ac:plain-text-body></ac:macro>

<p>Once an element has been added to the form, you can retrieve it by name. This can be done either by using the getElement() method or by using overloading to access the element as an object property:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// getElement():
$foo = $form->getElement('foo');
// As object property:
$foo = $form->foo;
{code}
]]></ac:plain-text-body></ac:macro>

h3. Populating and Retrieving Values
<h3>Populating and Retrieving Values</h3>

<p>After validating a form, you will typically need to retrieve the values so you can perform other operations, such as updating a database or notifying a web service. You can retrieve all values for all elements using getValues(); getValue($name) allows you to retrieve a single element's value by element name:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Get all values:
$values = $form->getValues();
// Get only 'foo' element's value:
$value = $form->getValue('foo');
{code}
]]></ac:plain-text-body></ac:macro>

<p>Sometimes you'll want to populate the form with specified values prior to rendering. This can be done with either the setDefaultValues() or populate() methods:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->setDefaultValues($data);
$form->populate($data);
{code}
]]></ac:plain-text-body></ac:macro>

h3. Global Operations
<h3>Global Operations</h3>
<p>Occasionally you will want certain operations to affect all elements. Common scenarios include needing to set plugin prefix paths for all elements, setting decorators for all elements, and setting filters for all elements. As examples:</p>

{info:title=Setting Prefix Paths for All Elements}
<ac:macro ac:name="info"><ac:parameter ac:name="title">Setting Prefix Paths for All Elements</ac:parameter><ac:rich-text-body>
<p>You can set prefix paths for all elements by type, or using a global prefix. As some examples:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Set global prefix path:
// Creates paths for prefixes My_Foo_Filter, My_Foo_Validate,
// Just decorator paths:
$form->addElementPrefixPath('My_Foo_Decorator', 'My/Foo/Decorator', 'decorator');
{code}
{info}
]]></ac:plain-text-body></ac:macro></ac:rich-text-body></ac:macro>

{info:title=Setting Decorators for All Elements}
<ac:macro ac:name="info"><ac:parameter ac:name="title">Setting Decorators for All Elements</ac:parameter><ac:rich-text-body>
<p>You can set decorators for all elements. setElementDecorators() accepts an array of decorators, just like setDecorators(), and will overwrite any previously set decorators in each element. In this example, we set the decorators to simply a ViewHelper and a Label:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->setElementDecorators(array(
'ViewHelper',
'Label'
));
{code}
{info}
]]></ac:plain-text-body></ac:macro></ac:rich-text-body></ac:macro>

{info:title=Setting Filters for All Elements}
<ac:macro ac:name="info"><ac:parameter ac:name="title">Setting Filters for All Elements</ac:parameter><ac:rich-text-body>
<p>In many cases, you may want to apply the same filter to all elements; a common case is to trim() all values:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->setElementFilters(array('StringTrim'));
{code}
{info}
]]></ac:plain-text-body></ac:macro></ac:rich-text-body></ac:macro>

h3. Methods For Interacting With Elements
<h3>Methods For Interacting With Elements</h3>
<p>The following methods may be used to interact with elements:</p>

* addElement($element, $name = null, $options = null)
* addElements(array $elements)
* setElements(array $elements)
* getElement($name)
* getElements()
* removeElement($name)
* clearElements()
* setDefaults(array $defaults)
* setDefault($name, $value)
* getValue($name)
* getValues()
* getUnfilteredValue($name)
* getUnfilteredValues()
* setElementFilters(array $filters)
* setElementDecorators(array $decorators)
* addElementPrefixPath($prefix, $path, $type = null)
* addElementPrefixPaths(array $spec)
<ul>
<li>addElement($element, $name = null, $options = null)</li>
<li>addElements(array $elements)</li>
<li>setElements(array $elements)</li>
<li>getElement($name)</li>
<li>getElements()</li>
<li>removeElement($name)</li>
<li>clearElements()</li>
<li>setDefaults(array $defaults)</li>
<li>setDefault($name, $value)</li>
<li>getValue($name)</li>
<li>getValues()</li>
<li>getUnfilteredValue($name)</li>
<li>getUnfilteredValues()</li>
<li>setElementFilters(array $filters)</li>
<li>setElementDecorators(array $decorators)</li>
<li>addElementPrefixPath($prefix, $path, $type = null)</li>
<li>addElementPrefixPaths(array $spec)</li>
</ul>

h2. Display Groups

Display groups are a way to create virtual groupings of elements for display purposes. All elements remain accessible by name in the form, but when iterating over the form or rendering, any elements in a display group are rendered together. The most common use case for this is for grouping elements in fieldsets.
<h2>Display Groups</h2>

The base class for display groups is Zend_Form_DisplayGroup. While it can be instantiated directly, it is typically best to use Zend_Form's addDisplayGroup() method to do so. This method takes an array of elements as its first argument, and a name for the display group as its second argument. You may optionally pass in an array of options or a Zend_Config object as the third argument.
<p>Display groups are a way to create virtual groupings of elements for display purposes. All elements remain accessible by name in the form, but when iterating over the form or rendering, any elements in a display group are rendered together. The most common use case for this is for grouping elements in fieldsets.</p>

Assuming that the elements 'username' and 'password' are already set in the form, the following code would group these elements in a 'login' display group:
<p>The base class for display groups is Zend_Form_DisplayGroup. While it can be instantiated directly, it is typically best to use Zend_Form's addDisplayGroup() method to do so. This method takes an array of elements as its first argument, and a name for the display group as its second argument. You may optionally pass in an array of options or a Zend_Config object as the third argument.</p>

<p>Assuming that the elements 'username' and 'password' are already set in the form, the following code would group these elements in a 'login' display group:</p>
{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form-addDisplayGroup(array('username', 'password'), 'login');
{code}
]]></ac:plain-text-body></ac:macro>

<p>You can access display groups using the getDisplayGroup() method, or via overloading using the display group's name:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Using getDisplayGroup():
$login = $form->getDisplayGroup('login');
// Using overloading:
$login = $form->login;
{code}
]]></ac:plain-text-body></ac:macro>

h3. Global Operations
<h3>Global Operations</h3>
<p>Just as with elements, there are some operations which might affect all display groups; these include setting decorators and setting the plugin path in which to look for decorators.</p>

{info:title=Setting Decorator Prefix Path for All Display Groups}
<ac:macro ac:name="info"><ac:parameter ac:name="title">Setting Decorator Prefix Path for All Display Groups</ac:parameter><ac:rich-text-body>
<p>By default, display groups inherit whichever decorator paths the form uses; however, if they should look in alternate locations, you can use the addDisplayGroupPrefixPath() method.</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->addDisplayGroupPrefixPath('My_Foo_Decorator', 'My/Foo/Decorator');
{code}
{info}
]]></ac:plain-text-body></ac:macro></ac:rich-text-body></ac:macro>

{info:title=Setting Decorators for All Display Groups}
<ac:macro ac:name="info"><ac:parameter ac:name="title">Setting Decorators for All Display Groups</ac:parameter><ac:rich-text-body>
<p>You can set decorators for all display groups. setDisplayGroupDecorators() accepts an array of decorators, just like setDecorators(), and will overwrite any previously set decorators in each display group. In this example, we set the decorators to simply a fieldset (the FormElements decorator is necessary to ensure that the elements are iterated):</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->setDisplayGroupDecorators(array(
'FormElements',
'Fieldset'
));
{code}
{info}
]]></ac:plain-text-body></ac:macro></ac:rich-text-body></ac:macro>

h3. Methods for Interacting With Display Groups
<h3>Methods for Interacting With Display Groups</h3>
<p>The following methods may be used to interact with display groups:</p>

* addDisplayGroup(array $elements, $name, $options = null)
* addDisplayGroups(array $groups)
* setDisplayGroups(array $groups)
* getDisplayGroup($name)
* getDisplayGroups()
* removeDisplayGroup($name)
* clearDisplayGroups()
* setDisplayGroupDecorators(array $decorators)
* addDisplayGroupPrefixPath($prefix, $path)
<ul>
<li>addDisplayGroup(array $elements, $name, $options = null)</li>
<li>addDisplayGroups(array $groups)</li>
<li>setDisplayGroups(array $groups)</li>
<li>getDisplayGroup($name)</li>
<li>getDisplayGroups()</li>
<li>removeDisplayGroup($name)</li>
<li>clearDisplayGroups()</li>
<li>setDisplayGroupDecorators(array $decorators)</li>
<li>addDisplayGroupPrefixPath($prefix, $path)</li>
</ul>

h3. Zend_Form_DisplayGroup Methods
Zend_Form_DisplayGroup has the following methods, grouped by type:

* *Configuration:*
** setOptions(array $options)
** setConfig(Zend_Config $config)
* *Metadata:*
** setAttrib($key, $value)
** addAttribs(array $attribs)
** setAttribs(array $attribs)
** getAttrib($key)
** getAttribs()
** removeAttrib($key)
** clearAttribs()
** setName($name)
** getName()
** setLegend($legend)
** getLegend()
** setOrder($order)
** getOrder()
* *Elements:*
** addElement(Zend_Form_Element $element)
** addElements(array $elements)
** setElements(array $elements)
** getElement($name)
** getElements()
** removeElement($name)
** clearElements()
* *Plugin loaders:*
** setPluginLoader(Zend_Loader_PluginLoader $loader)
** getPluginLoader()
** addPrefixPath($prefix, $path)
** addPrefixPaths(array $spec)
* *Decorators:*
** addDecorator($decorator, $options = null)
** addDecorators(array $decorators)
** setDecorators(array $decorators)
** getDecorator($name)
** getDecorators()
** removeDecorator($name)
** clearDecorators()
* *Rendering:*
** setView(Zend_View_Interface $view = null)
** getView()
** render(Zend_View_Interface $view = null)
* *I18N:*
** setTranslator(Zend_Translate_Adapter $translator = null)
** getTranslator()
<h3>Zend_Form_DisplayGroup Methods</h3>
<p>Zend_Form_DisplayGroup has the following methods, grouped by type:</p>

h2. Sub Forms
<ul>
<li><strong>Configuration:</strong>
<ul>
<li>setOptions(array $options)</li>
<li>setConfig(Zend_Config $config)</li>
</ul>
</li>
<li><strong>Metadata:</strong>
<ul>
<li>setAttrib($key, $value)</li>
<li>addAttribs(array $attribs)</li>
<li>setAttribs(array $attribs)</li>
<li>getAttrib($key)</li>
<li>getAttribs()</li>
<li>removeAttrib($key)</li>
<li>clearAttribs()</li>
<li>setName($name)</li>
<li>getName()</li>
<li>setLegend($legend)</li>
<li>getLegend()</li>
<li>setOrder($order)</li>
<li>getOrder()</li>
</ul>
</li>
<li><strong>Elements:</strong>
<ul>
<li>addElement(Zend_Form_Element $element)</li>
<li>addElements(array $elements)</li>
<li>setElements(array $elements)</li>
<li>getElement($name)</li>
<li>getElements()</li>
<li>removeElement($name)</li>
<li>clearElements()</li>
</ul>
</li>
<li><strong>Plugin loaders:</strong>
<ul>
<li>setPluginLoader(Zend_Loader_PluginLoader $loader)</li>
<li>getPluginLoader()</li>
<li>addPrefixPath($prefix, $path)</li>
<li>addPrefixPaths(array $spec)</li>
</ul>
</li>
<li><strong>Decorators:</strong>
<ul>
<li>addDecorator($decorator, $options = null)</li>
<li>addDecorators(array $decorators)</li>
<li>setDecorators(array $decorators)</li>
<li>getDecorator($name)</li>
<li>getDecorators()</li>
<li>removeDecorator($name)</li>
<li>clearDecorators()</li>
</ul>
</li>
<li><strong>Rendering:</strong>
<ul>
<li>setView(Zend_View_Interface $view = null)</li>
<li>getView()</li>
<li>render(Zend_View_Interface $view = null)</li>
</ul>
</li>
<li><strong>I18N:</strong>
<ul>
<li>setTranslator(Zend_Translate_Adapter $translator = null)</li>
<li>getTranslator()</li>
</ul>
</li>
</ul>

Sub forms serve several purposes:

* Creating logical element groups. Since sub forms are simply forms, you can validate subforms as individual entities.
* Creating multi-page forms. Since sub forms are simply forms, you can display a separate sub form per page, building up multi-page forms where each form has its own validation logic. Only once all sub forms validate would the form be considered complete.
* Display groupings. Like display groups, sub forms, when rendered as part of a larger form, can be used to group elements. Be aware, however, that the master form object will have no awareness of the elements in sub forms.
<h2>Sub Forms</h2>

A sub form may be a Zend_Form object, or, more typically, a Zend_Form_SubForm object. The latter contains decorators suitable for inclusion in a larger form (i.e., it does not render additional HTML form tags, but does group elements). To attach a sub form, simply add it to the form and give it a name:
<p>Sub forms serve several purposes:</p>

{code:php} <ul>
<li>Creating logical element groups. Since sub forms are simply forms, you can validate subforms as individual entities.</li>
<li>Creating multi-page forms. Since sub forms are simply forms, you can display a separate sub form per page, building up multi-page forms where each form has its own validation logic. Only once all sub forms validate would the form be considered complete.</li>
<li>Display groupings. Like display groups, sub forms, when rendered as part of a larger form, can be used to group elements. Be aware, however, that the master form object will have no awareness of the elements in sub forms.</li>
</ul>


<p>A sub form may be a Zend_Form object, or, more typically, a Zend_Form_SubForm object. The latter contains decorators suitable for inclusion in a larger form (i.e., it does not render additional HTML form tags, but does group elements). To attach a sub form, simply add it to the form and give it a name:</p>

<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->addSubForm($subForm, 'subform');
{code}
]]></ac:plain-text-body></ac:macro>

<p>You can retrieve a sub form using either getSubForm($name) or overloading using the sub form name:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Using getSubForm():
$subForm = $form->getSubForm('subform');
// Using overloading:
$subForm = $form->subform;
{code}
]]></ac:plain-text-body></ac:macro>

<p>Sub forms are included in form iteration, though the elements it contains are not.</p>

h3. Global Operations
<h3>Global Operations</h3>
<p>Like elements and display groups, there are some operations that might need to affect all sub forms. Unlike display groups and elements, however, sub forms inherit most functionality from the master form object, and the only real operation that may need to be performed globally is setting decorators for sub forms. For this purpose, there is the setSubFormDecorators() method. In the next example, we'll set the decorator for all subforms to be simply a fieldset (the FormElements decorator is needed to ensure its elements are iterated):</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->setSubFormsDecorators(array(
'FormElements',
'Fieldset'
));
{code}
]]></ac:plain-text-body></ac:macro>

h3. Methods for Interacting With Sub Forms
<h3>Methods for Interacting With Sub Forms</h3>
<p>The following methods may be used to interact with sub forms:</p>

* addSubForm(Zend_Form $form, $name, $order = null)
* addSubForms(array $subForms)
* setSubForms(array $subForms)
* getSubForm($name)
* getSubForms()
* removeSubForm($name)
* clearSubForms()
* setSubFormDecorators(array $decorators)
<ul>
<li>addSubForm(Zend_Form $form, $name, $order = null)</li>
<li>addSubForms(array $subForms)</li>
<li>setSubForms(array $subForms)</li>
<li>getSubForm($name)</li>
<li>getSubForms()</li>
<li>removeSubForm($name)</li>
<li>clearSubForms()</li>
<li>setSubFormDecorators(array $decorators)</li>
</ul>

h2. Metadata and Attributes

While a form's usefulness primarily derives from the elements it contains, it can also contain other metadata, such as a name (often used as a unique ID in the HTML markup); the form action and method; the number of elements, groups, and sub forms it contains; and arbitrary metadata (usually used to set HTML attributes for the form tag itself).
<h2>Metadata and Attributes</h2>

You can set and retrieve a form's name using the name accessors:
<p>While a form's usefulness primarily derives from the elements it contains, it can also contain other metadata, such as a name (often used as a unique ID in the HTML markup); the form action and method; the number of elements, groups, and sub forms it contains; and arbitrary metadata (usually used to set HTML attributes for the form tag itself).</p>

<p>You can set and retrieve a form's name using the name accessors:</p>
{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Set the name:
$form->setName('registration');
// Retrieve the name:
$name = $form->getName();
{code}
]]></ac:plain-text-body></ac:macro>

<p>To set the action (url to which the form submits) and method (method by which it should submit, e.g., 'POST' or 'GET'), use the action and method accessors:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Set the action and method:
$form->setAction('/user/login')
->setMethod('post');
{code}
]]></ac:plain-text-body></ac:macro>

{note}
<ac:macro ac:name="note"><ac:rich-text-body>
<p>The method and action are only used internally for rendering, and not for any sort of validation.</p></ac:rich-text-body></ac:macro>
{note}

<p>Zend_Form implements the Countable interface, allowing you to pass it as an argument to count:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$numItems = count($form);
{code}
]]></ac:plain-text-body></ac:macro>

<p>Setting arbitrary metadata is done through the attribs accessors. Since overloading in Zend_Form is used to access elements, display groups, and sub forms, this is the only method for accessing metadata.</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// Setting attributes:
$form->setAttrib('class', 'zend-form')
// Clear all attributes:
$form->clearAttribs();
{code}
]]></ac:plain-text-body></ac:macro>

h2. Decorators
<h2>Decorators</h2>

<p>Creating the markup for a form is often a time-consuming task, particularly if you plan on re-using the same markup to show things such as validation errors, submitted values, etc. Zend_Form's answer to this issue is decorators.</p>

<p>Decorators for Zend_Form objects can be used to render a form. The FormElements decorator will iterate through all items in a form -- &ndash; elements, display groups, and sub forms -- &ndash; and render them, returning the result. Additional decorators may then be used to wrap this content, or append or prepend it.</p>

<p>The default decorators for Zend_Form are FormElements, HtmlTag (wraps in a definition list), and Form; the equivalent code for creating them is as follows:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form->setDecorators(array(
'FormElements',
'Form'
));
{code}
]]></ac:plain-text-body></ac:macro>

This creates output like the following:
<p>This creates output like the following:</p>

{code:html}
<ac:macro ac:name="code"><ac:default-parameter>html</ac:default-parameter><ac:plain-text-body><![CDATA[
<form action="/form/action" method="post">
<dl>
</dl>
</form>
{code}
]]></ac:plain-text-body></ac:macro>

<p>Any attributes set on the form object will be used as HTML attributes of the &lt;form&gt; tag.</p>

<p>You may create your own decorators for generating the form. One common use case is if you know the exact HTML you wish to use; your decorator could create the exact HTML and simply return it, potentially using the decorators from individual elements or display groups.</p>

<p>The following methods may be used to interact with decorators:</p>

* addDecorator($decorator, $options = null)
* addDecorators(array $decorators)
* setDecorators(array $decorators)
* getDecorator($name)
* getDecorators()
* removeDecorator($name)
* clearDecorators()
<ul>
<li>addDecorator($decorator, $options = null)</li>
<li>addDecorators(array $decorators)</li>
<li>setDecorators(array $decorators)</li>
<li>getDecorator($name)</li>
<li>getDecorators()</li>
<li>removeDecorator($name)</li>
<li>clearDecorators()</li>
</ul>

h2. Validation

A primary use case for forms is validating submitted data. Zend_Form allows you to validate an entire form at once or a partial form, as well as to automate validation responses for XmlHttpRequests (AJAX). If the submitted data is not valid, it has methods for retrieving the various error codes and messages for elements and sub forms failing validations.
<h2>Validation</h2>

To validate a full form, use the isValid() method:
<p>A primary use case for forms is validating submitted data. Zend_Form allows you to validate an entire form at once or a partial form, as well as to automate validation responses for XmlHttpRequests (AJAX). If the submitted data is not valid, it has methods for retrieving the various error codes and messages for elements and sub forms failing validations.</p>

<p>To validate a full form, use the isValid() method:</p>
{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
if (!$form->isValid($_POST)) {
// failed validation
}
{code}
]]></ac:plain-text-body></ac:macro>

<p>isValid() will validate every required element, and any unrequired element contained in the submitted data.</p>

<p>Sometimes you may need to validate only a subset of the data; for this, use isValidPartial($data):</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
if (!$form->isValidPartial($data)) {
// failed validation
}
{code}
]]></ac:plain-text-body></ac:macro>

<p>isValidPartial() only attempts to validate those items in the data for which there are matching elements; if an element is not represented in the data, it is skipped.</p>

<p>When validating elements or groups of elements for an AJAX request, you will typically be validating a subset of the form, and want the response back in JSON. processAjax() does precisely that:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$json = $form->processAjax($data);
{code}
]]></ac:plain-text-body></ac:macro>

<p>You can then simply send the JSON response to the client. If the form is valid, this will be a boolean true response. If not, it will be a javascript object containing key/message pairs, where each 'message' is an array of validation error messages.</p>

<p>For forms that fail validation, you can retrieve both error codes and error messages, using getErrors() and getMessages(), respectively:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$codes = $form->getErrors();
$messages = $form->getMessage();
{code}
]]></ac:plain-text-body></ac:macro>

{note}
<ac:macro ac:name="note"><ac:rich-text-body>
<p>Since the messages returned by getMessages() are an array of error code/message pairs, getErrors() is typically not needed.</p></ac:rich-text-body></ac:macro>
{note}

<p>You can retrieve codes and error messages for individual elements by simply passing the element name to each:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$codes = $form->getErrors('username');
$messages = $form->getMessages('username');
{code}
]]></ac:plain-text-body></ac:macro>

{note}
<ac:macro ac:name="note"><ac:rich-text-body>
<p>When validating elements, Zend_Form sends a second argument to each element's isValid() method: the array of data being validated. This can then be used by individual validators to allow them to utilize other submitted values when determining the validity of the data. An example would be a registration form that requires both a password and password confirmation; the password element could use the password confirmation as part of its validation. </p></ac:rich-text-body></ac:macro>
{note}

h2. Methods
<h2>Methods</h2>

<p>The following is a full list of methods available to Zend_Form, grouped by type:</p>

* *Configuration and Options:*
** setOptions(array $options)
** setConfig(Zend_Config $config)
* *Plugin Loaders and paths:*
** setPluginLoader(Zend_Loader_PluginLoader_Interface $loader, $type = null)
** getPluginLoader($type = null)
** addPrefixPath($prefix, $path, $type = null)
** addPrefixPaths(array $spec)
** addElementPrefixPath($prefix, $path, $type = null)
** addElementPrefixPaths(array $spec)
** addDisplayGroupPrefixPath($prefix, $path)
* *Metadata:*
** setAttrib($key, $value)
** addAttribs(array $attribs)
** setAttribs(array $attribs)
** getAttrib($key)
** getAttribs()
** removeAttrib($key)
** clearAttribs()
** setAction($action)
** getAction()
** setMethod($method)
** getMethod()
** setName($name)
** getName()
* *Elements:*
** addElement($element, $name = null, $options = null)
** addElements(array $elements)
** setElements(array $elements)
** getElement($name)
** getElements()
** removeElement($name)
** clearElements()
** setDefaults(array $defaults)
** setDefault($name, $value)
** getValue($name)
** getValues()
** getUnfilteredValue($name)
** getUnfilteredValues()
** setElementFilters(array $filters)
** setElementDecorators(array $decorators)
* *Sub forms:*
** addSubForm(Zend_Form $form, $name, $order = null)
** addSubForms(array $subForms)
** setSubForms(array $subForms)
** getSubForm($name)
** getSubForms()
** removeSubForm($name)
** clearSubForms()
** setSubFormDecorators(array $decorators)
* *Display groups:*
** addDisplayGroup(array $elements, $name, $options = null)
** addDisplayGroups(array $groups)
** setDisplayGroups(array $groups)
** getDisplayGroup($name)
** getDisplayGroups()
** removeDisplayGroup($name)
** clearDisplayGroups()
** setDisplayGroupDecorators(array $decorators)
* *Validation*
** populate(array $values)
** isValid(array $data)
** isValidPartial(array $data)
** processAjax(array $data)
** persistData()
** getErrors($name = null)
** getMessages($name = null)
* *Rendering:*
** setView(Zend_View_Interface $view = null)
** getView()
** addDecorator($decorator, $options = null)
** addDecorators(array $decorators)
** setDecorators(array $decorators)
** getDecorator($name)
** getDecorators()
** removeDecorator($name)
** clearDecorators()
** render(Zend_View_Interface $view = null)
* *I18N:*
** setTranslator(Zend_Translate_Adapter $translator = null)
** getTranslator()
<ul>
<li><strong>Configuration and Options:</strong>
<ul>
<li>setOptions(array $options)</li>
<li>setConfig(Zend_Config $config)</li>
</ul>
</li>
<li><strong>Plugin Loaders and paths:</strong>
<ul>
<li>setPluginLoader(Zend_Loader_PluginLoader_Interface $loader, $type = null)</li>
<li>getPluginLoader($type = null)</li>
<li>addPrefixPath($prefix, $path, $type = null)</li>
<li>addPrefixPaths(array $spec)</li>
<li>addElementPrefixPath($prefix, $path, $type = null)</li>
<li>addElementPrefixPaths(array $spec)</li>
<li>addDisplayGroupPrefixPath($prefix, $path)</li>
</ul>
</li>
<li><strong>Metadata:</strong>
<ul>
<li>setAttrib($key, $value)</li>
<li>addAttribs(array $attribs)</li>
<li>setAttribs(array $attribs)</li>
<li>getAttrib($key)</li>
<li>getAttribs()</li>
<li>removeAttrib($key)</li>
<li>clearAttribs()</li>
<li>setAction($action)</li>
<li>getAction()</li>
<li>setMethod($method)</li>
<li>getMethod()</li>
<li>setName($name)</li>
<li>getName()</li>
</ul>
</li>
<li><strong>Elements:</strong>
<ul>
<li>addElement($element, $name = null, $options = null)</li>
<li>addElements(array $elements)</li>
<li>setElements(array $elements)</li>
<li>getElement($name)</li>
<li>getElements()</li>
<li>removeElement($name)</li>
<li>clearElements()</li>
<li>setDefaults(array $defaults)</li>
<li>setDefault($name, $value)</li>
<li>getValue($name)</li>
<li>getValues()</li>
<li>getUnfilteredValue($name)</li>
<li>getUnfilteredValues()</li>
<li>setElementFilters(array $filters)</li>
<li>setElementDecorators(array $decorators)</li>
</ul>
</li>
<li><strong>Sub forms:</strong>
<ul>
<li>addSubForm(Zend_Form $form, $name, $order = null)</li>
<li>addSubForms(array $subForms)</li>
<li>setSubForms(array $subForms)</li>
<li>getSubForm($name)</li>
<li>getSubForms()</li>
<li>removeSubForm($name)</li>
<li>clearSubForms()</li>
<li>setSubFormDecorators(array $decorators)</li>
</ul>
</li>
<li><strong>Display groups:</strong>
<ul>
<li>addDisplayGroup(array $elements, $name, $options = null)</li>
<li>addDisplayGroups(array $groups)</li>
<li>setDisplayGroups(array $groups)</li>
<li>getDisplayGroup($name)</li>
<li>getDisplayGroups()</li>
<li>removeDisplayGroup($name)</li>
<li>clearDisplayGroups()</li>
<li>setDisplayGroupDecorators(array $decorators)</li>
</ul>
</li>
<li><strong>Validation</strong>
<ul>
<li>populate(array $values)</li>
<li>isValid(array $data)</li>
<li>isValidPartial(array $data)</li>
<li>processAjax(array $data)</li>
<li>persistData()</li>
<li>getErrors($name = null)</li>
<li>getMessages($name = null)</li>
</ul>
</li>
<li><strong>Rendering:</strong>
<ul>
<li>setView(Zend_View_Interface $view = null)</li>
<li>getView()</li>
<li>addDecorator($decorator, $options = null)</li>
<li>addDecorators(array $decorators)</li>
<li>setDecorators(array $decorators)</li>
<li>getDecorator($name)</li>
<li>getDecorators()</li>
<li>removeDecorator($name)</li>
<li>clearDecorators()</li>
<li>render(Zend_View_Interface $view = null)</li>
</ul>
</li>
<li><strong>I18N:</strong>
<ul>
<li>setTranslator(Zend_Translate_Adapter $translator = null)</li>
<li>getTranslator()</li>
</ul>
</li>
</ul>

h2. Configuration

Zend_Form is fully configurable via setOptions() and setConfig() (or by passing options or a Zend_Config object to the constructor). Using these methods, you can specify form elements, display groups, decorators, and metadata.
<h2>Configuration</h2>

As a general rule, if 'set' + the option key refers to a Zend_Form method, then the value provided will be passed to that method.
<p>Zend_Form is fully configurable via setOptions() and setConfig() (or by passing options or a Zend_Config object to the constructor). Using these methods, you can specify form elements, display groups, decorators, and metadata.</p>

Exceptions to the rule include the following:
<p>As a general rule, if 'set' + the option key refers to a Zend_Form method, then the value provided will be passed to that method.</p>

* prefixPaths will be passed to addPrefixPaths()
* elementPrefixPaths will be passed to addElementPrefixPaths()
* displayGroupPrefixPaths will be passed to addDisplayGroupPrefixPaths()
* the following setters cannot be set in this way:
** setAttrib (though setAttribs *will* work)
** setConfig
** setDefault
** setOptions
** setPluginLoader
** setSubForms
** setTranslator
** setView
<p>Exceptions to the rule include the following:</p>

As an example, here is a config file that passes configuration for every type of configurable data:
<ul>
<li>prefixPaths will be passed to addPrefixPaths()</li>
<li>elementPrefixPaths will be passed to addElementPrefixPaths()</li>
<li>displayGroupPrefixPaths will be passed to addDisplayGroupPrefixPaths()</li>
<li>the following setters cannot be set in this way:
<ul>
<li>setAttrib (though setAttribs <strong>will</strong> work)</li>
<li>setConfig</li>
<li>setDefault</li>
<li>setOptions</li>
<li>setPluginLoader</li>
<li>setSubForms</li>
<li>setTranslator</li>
<li>setView</li>
</ul>
</li>
</ul>

{code:ini}
<p>As an example, here is a config file that passes configuration for every type of configurable data:</p>

<ac:macro ac:name="code"><ac:default-parameter>ini</ac:default-parameter><ac:plain-text-body><![CDATA[
[element]
name = "registration"
decorators.fieldset.decorator.options.class = "zend_form"
decorators.form.decorator = "Form"
{code}
]]></ac:plain-text-body></ac:macro>

<p>The above could easily be abstracted to an XML or PHP array-based configuration file.</p>

h2. Custom forms
<h2>Custom forms</h2>

<p>An alternative to using configuration-based forms is to subclass Zend_Form. This has several benefits:</p>

<ul>
* You <li>You can unit test your form easily to ensure validations and rendering perform as expected.</li>
* Fine-grained control over individual elements.
<li>Fine-grained control over individual elements.</li>
* Re-use <li>Re-use of form objects, and greater portability (no need to track config files).</li>
* Implementing custom functionality.
<li>Implementing custom functionality.</li>
</ul>

The most typical use case would be to use the constructor to setup specific form elements and configuration:

<p>The most typical use case would be to use the constructor to setup specific form elements and configuration:</p>
{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
class My_Form_Login extends Zend_Form
{
}
}
{code}
]]></ac:plain-text-body></ac:macro>

<p>This form can then be instantiated with simply:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form = new My_Form_Login();
{code}
]]></ac:plain-text-body></ac:macro>

<p>and all functionality is already setup and ready; no config files needed. (Note that this example is greatly simplified, as it contains no validators or filters for the elements.)</p>

h1. Creating Custom Form Markup Using Zend_Form_Decorator
<h1>Creating Custom Form Markup Using Zend_Form_Decorator</h1>

<p>Rendering a form object is completely optional -- &ndash; you do not need to use Zend_Form's render() methods at all. However, if you do, decorators are used to render the various form objects. </p>

<p>An arbitrary number of decorators may be attached to each item (elements, display groups, sub forms, or the form object itself); however, only one decorator of a given type may be attached to each item. Decorators are called in the order they are registered. Depending on the decorator, it may replace the content passed to it, or append or prepend the content.</p>

<p>Object state is set via configuration options passed to the constructor or the decorator's setOptions() method. When creating decorators via an item's addDecorator() or related methods, options may be passed as an argument to the method. These can be used to specify placement, a separator to use between passed in content and newly generated content, and whatever options the decorator supports.</p>

<p>Before each decorator's render() method is called, the current item is set in the decorator using setElement(), giving the decorator awareness of the item being rendered. This allows you to create decorators that only render specific portions of the item -- &ndash; such as the label, the value, error messages, etc. By stringing together several decorators that render specific element segments, you can build complex markup representing the entire item.</p>

h2. Operation
<h2>Operation</h2>

<p>To configure a decorator, pass an array of options or a Zend_Config object to its constructor, an array to setOptions(), or a Zend_Config object to setConfig().</p>

Standard options include:
<p>Standard options include:</p>
<ul>
* placement: <li>placement: Placement can be either 'append' or 'prepend' (case insensitive), and indicates whether content passed to render() will be appended or prepended, respectively. In the case that a decorator replaces the content, this setting is ignored. The default setting is to append.</li>
* separator: <li>separator: The separator is used between the content passed to render() and new content generated by the decorator, or between items rendered by the decorator (e.g. FormElements uses the separator between each item rendered). In the case that a decorator replaces the content, this setting may be ignored. The default value is PHP_EOL.</li>
</ul>

The decorator interface specifies methods for interacting with options. These include:

* setOption($key, $value): set a single option.
* getOption($key): retrieve a single option value.
* getOptions(): retrieve all options.
* removeOption($key): remove a single option.
* clearOptions(): remove all options.
<p>The decorator interface specifies methods for interacting with options. These include:</p>

Decorators are meant to interact with the various Zend_Form class types: Zend_Form, Zend_Form_Element, Zend_Form_DisplayGroup, and all classes deriving from them. The method setElement() allows you to set the object the decorator is currently working with, and getElement() is used to retrieve it.
<ul>
<li>setOption($key, $value): set a single option.</li>
<li>getOption($key): retrieve a single option value.</li>
<li>getOptions(): retrieve all options.</li>
<li>removeOption($key): remove a single option.</li>
<li>clearOptions(): remove all options.</li>
</ul>

Each decorator's render() method accepts a string, $content. When the first decorator is called, this string is typically empty, while on subsequent calls it will be populated. Based on the type of decorator and the options passed in, the decorator will either replace this string, prepend the string, or append the string; an optional separator will be used in the latter two situations.

h2. Standard Decorators
<p>Decorators are meant to interact with the various Zend_Form class types: Zend_Form, Zend_Form_Element, Zend_Form_DisplayGroup, and all classes deriving from them. The method setElement() allows you to set the object the decorator is currently working with, and getElement() is used to retrieve it.</p>

Zend_Form ships with several standard decorators.
<p>Each decorator's render() method accepts a string, $content. When the first decorator is called, this string is typically empty, while on subsequent calls it will be populated. Based on the type of decorator and the options passed in, the decorator will either replace this string, prepend the string, or append the string; an optional separator will be used in the latter two situations.</p>

h3. Callback
<h2>Standard Decorators</h2>

The Callback decorator can execute an arbitrary callback to render content. Callbacks should be specified via the 'callback' option passed in the decorator configuration, and can be any valid PHP callback type. Callbacks should accept three arguments, $content (the original content passed to the decorator), $element (the item being decorated), and an array of $options. As an example callback:
<p>Zend_Form ships with several standard decorators.</p>

{code:php} <h3>Callback</h3>

<p>The Callback decorator can execute an arbitrary callback to render content. Callbacks should be specified via the 'callback' option passed in the decorator configuration, and can be any valid PHP callback type. Callbacks should accept three arguments, $content (the original content passed to the decorator), $element (the item being decorated), and an array of $options. As an example callback:</p>

<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
class Util
{
}
}
{code}
]]></ac:plain-text-body></ac:macro>

<p>This callback would be specified as array('Util', 'label'), and would generate some (bad) HTML markup for the label. The Callback decorator would then either replace, append, or prepend the original content with the return value of this.</p>

<p>The Callback decorator allows specifying a null value for the placement option, which will replace the original content with the callback return value; 'prepend' and 'append' are still valid as well.</p>

h3. DtDdWrapper
<h3>DtDdWrapper</h3>

<p>The default decorators utilize definition lists (&lt;dl&gt;) to render form elements. Since form items can appear in any order, display groups and sub forms can be interspersed with other form items. To keep these particular item types within the definition list, the DtDdWrapper creates a new, empty definition term (&lt;dt&gt;) and wraps its content in a new definition datum (&lt;dd&gt;). The output looks something like this:</p>

{code:html}
<ac:macro ac:name="code"><ac:default-parameter>html</ac:default-parameter><ac:plain-text-body><![CDATA[
<dt></dt>
<dd><fieldset id="subform">
...
</fieldset></dd>
{code}
]]></ac:plain-text-body></ac:macro>

<p>This decorator replaces the content provided to it by wrapping it within the &lt;dd&gt; element.</p>

h3. Errors
<h3>Errors</h3>

<p>Element errors get their own decorator with the Errors decorator. This decorator proxies to the FormErrors view helper, which renders error messages in an unordered list (&lt;ul&gt;) as list items. The &lt;ul&gt; element receives a class of "errors". &quot;errors&quot;.</p>

<p>The Errors decorator can either prepend or append the content provided to it.</p>

h3. Fieldset
<h3>Fieldset</h3>

<p>Display groups and sub forms render their content within fieldsets by default. The Fieldset decorator checks for either a 'legend' option or a getLegend() method in the registered element, and uses that as a legend if non-empty. Any content passed in is wrapped in the HTML fieldset, replacing the original content. Any attributes set in the decorated item are passed to the fieldset as HTML attributes.</p>

h3. Form
<h3>Form</h3>

<p>Zend_Form objects typically need to render an HTML form tag. The Form decorator proxies to the Form view helper. It wraps any provided content in an HTML form element, using the Zend_Form object's action and method, and any attributes as HTML attributes.</p>

h3. FormElements
<h3>FormElements</h3>

<p>Forms, display groups, and sub forms are collections of elements. In order to render these elements, they utilize the FormElements decorator, which iterates through all items, calling render() on each and joining them with the registered separator. It can either append or prepend content passed to it.</p>

h3. HtmlTag
<h3>HtmlTag</h3>

<p>The HtmlTag decorator allows you to utilize HTML tags to decorate content; the tag utilized is passed in the 'tag' option, and any other options are used as HTML attributes to that tag. The tag by default is assumed to be block level, and replaces the content by wrapping it in the given tag. However, you can specify a placement to append or prepend a tag as well.</p>

h3. Label
<h3>Label</h3>

<p>Form elements typically have labels, and the Label decorator is used to render these labels. It proxies to the FormLabel view helper, and pulls the element label using the getLabel() method of the element. If no label is present, none is rendered.</p>

<p>You may optionally specify a 'tag' option; if provided, it wraps the label in that block-level tag. If the 'tag' option is present, and no label present, the tag is rendered with no content.</p>

<p>By default, the Label decorator prepends to the provided content; specify a 'placement' option of 'append' to place it after the content.</p>

h3. ViewHelper
<h3>ViewHelper</h3>

<p>Most elements utilize Zend_View helpers for rendering, and this is done with the ViewHelper decorator. With it, you may specify a 'helper' tag to explicitly set the view helper to utilize; if none is provided, it uses the last segment of the element's class name to determine the helper, prepending it with the string 'form': e.g., 'Zend_Form_Element_Text' would look for a view helper of 'formText'. </p>

<p>Any attributes of the provided element are passed to the view helper as element attributes.</p>

<p>By default, this decorator appends content; use the 'placement' option to specify alternate placement.</p>

h2. Custom Decorators
<h2>Custom Decorators</h2>

<p>If you find your rendering needs are complex or need heavy customization, or if you need to use multiple decorators of the same type, you should consider creating a custom decorator.</p>

<p>Decorators need only implement Zend_Decorator_Interface. The interface specifies the following:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
interface Zend_Form_Decorator_Interface
{
public function render($content);
}
{code}
]]></ac:plain-text-body></ac:macro>

<p>To make this simpler, you can simply extend Zend_Decorator_Abstract, which implements all methods except render(). </p>

<p>As an example, if you wanted to have labels append a ':', and also display a '*' when required, you could write a decorator like the following:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
class My_Decorator_Label extends Zend_Form_Decorator_Abstract
{
}
}
{code}
]]></ac:plain-text-body></ac:macro>

<p>You can then place this in the decorator path:</p>

{code:php}
<ac:macro ac:name="code"><ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
// for an element:
$element->addPrefixPath('My_Decorator', 'My/Decorator/', 'decorator');
// for all elements:
$form->addElementPrefixPath('My_Decorator', 'My/Decorator/', 'decorator');
{code}
]]></ac:plain-text-body></ac:macro>

<p>In this particular example, because the decorator's final segment, 'Label' matches the same as Zend_Form_Decorator_Label, it will be rendered *in <strong>in place of* of</strong> that decorator -- &ndash; meaning you would not need to change any decorators to modify the output. (Needless to say, you can create decorators with different names; this simply shows how you can quickly and simply override existing rendering functionality through custom decorators.)</p>