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.
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:
Once this has been done, you should be able to test Zend_Form without issue.
Zend_Form simplifies form creation and handling in your web application. It accomplishes the following goals:
- Element validation
- Element filtering
- Element ordering
- Element and Form rendering
- Element and form grouping
- Element and form-level configuration
It heavily leverages other Zend Framework components to accomplish its goals, including Zend_Config, Zend_Validate, Zend_Filter, and optionally Zend_View.
Creating a form object is very simple: simply instantiate Zend_Form:
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.
If you wish to specify the form action and method (always good ideas), you can do so with the setAction() and setMethod() accessors:
The above code sets the form action to the partial URL "/resource/process" and the form method to HTTP POST. This will be reflected during final rendering.
You can set additional HTML attributes for the <form> tag using the setAttrib() or setAttribs() methods. For instance, if you wish to set the id, set the "id" property:
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:
- select (both regular and multi-select types)
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.
As some examples:
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.
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:
When using this second option, if the validator can accept constructor arguments, you can pass those in an array as the third parameter:
(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.)
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:
Filters are registered in basically the same way as validators. For illustration purposes, let's add a filter to lowercase the final value:
So, our final element setup might look like this:
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:
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.
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.
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:
Under the hood, Zend_Form uses "decorators" 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:
(where <HELPERNAME> is the name of a view helper to use, and varies based on the element.)
The above creates output like the following:
(albeit not with the same formatting.)
You can change the decorators used by an element if you wish to have different output; see the section on decorators for more information.
The form itself simply loops through the elements, and dresses them in an HTML <form>. The action and method you provided when setting up the form are provided to the <form> tag, as are any attributes you set via setAttribs() and family.
Elements are looped either in the order in which they were registered, or, if your element contains an order attribute, that order will be used. You can set an element's order using:
Or, when creating an element, by passing it as an option:
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.
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):
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:
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.
Assuming your validations have passed, you can now fetch the filtered values:
If you need the unfiltered values at any point, use:
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:
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.
Let's build a simple login form. It will need elements representing:
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.
We'll use the power of Zend_Form's configuration options to build the form:
Next, we'll create a controller for handling this:
And a view script for displaying the form:
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.
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'):
You could then pass this to the form constructor:
and the entire form will be defined.
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:
- validation (is submitted data valid?)
- capturing of validation error codes and messages
- filtering (how is the element escaped or normalized for output?)
- rendering (how is the element displayed?)
- metadata and attributes (what information further qualifies the element?)
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.
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.
The following loader types are used with the various plugin loader methods: 'validate', 'filter', and 'decorator'. The type names are case insensitive.
The methods used to interact with plugin loaders are as follows:
- 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'.
Custom validators, filters, and decorators are an easy way to share functionality between forms and encapsulate custom functionality.
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.
Validators may be added to the chain in two ways:
- passing in a concrete validator instance
- providing a validator name – either a short name or fully qualified class name
Let's see some examples:
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.
|Using Custom Validator Classes|
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:
(Recall that the third argument indicates which plugin loader on which to perform the action.)
If failing a particular validation should prevent later validators from firing, pass boolean true as the second parameter:
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:
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:
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():
If you want to be more verbose or explicit, you can use the array keys 'validator', 'breakChainOnFailure', and 'options':
This usage is good for illustrating how you could then configure validators in a config file:
Notice that every item has a key, whether or not it needs one; this is a limitation of using configuration files – but it also helps make explicit what the arguments are for. Just remember that any validator options must be specified in order.
To validate an element, pass the value to validate to isValid():
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:
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.
After a failed validation, you can retrieve the error codes and messages from the validator chain:
(Note: error messages returned are an associative array of error code / error message pairs.)
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.
For more information on validators, see the Zend_Validate documentation.
Methods associated with validation include:
- 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)
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():
Filters may be added to the chain in two ways:
- passing in a concrete filter instance
- providing a filter name – either a short name or fully qualified class name
Let's see some examples:
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.
|Using Custom Filter Classes|
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:
(Recall that the third argument indicates which plugin loader on which to perform the action.)
If at any time you need the unfiltered value, use the getUnfilteredValue() method:
For more information on filters, see the Zend_Filter documentation.
Methods associated with filters include:
- 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)
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.
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.
The default decorators used by Zend_Form_Element are:
- ViewHelper: specifies a view helper to use to render the element
- Label: prepends a label to the element using Zend_View_Helper_FormLabel. If no label is present, none is rendered.
- Errors: appends error messages to the element using Zend_View_Helper_FormErrors. If none are present, nothing is appended.
- HtmlTag: wraps the label, element, and errors in an HTML div, with the class attribute set to "form element".
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:
The initial content is created by the 'viewHelper' decorator, which creates the form element itself. The next decorator, 'label', retrieves the element's label and passes it to the 'formLabel' view helper; the value is prepended to the content by default. Next, the 'errors' decorator fetches error messages from the element, and, if any are present, passes them to the 'formErrors' view helper to render; this content is then appended to the previous content. Finally, the 'htmlTag' decorator takes the existing content, and wraps it in a 'div' tag that has the class 'form element'. The resulting output looks basically like this:
For more information on decorators, read the Zend_Form_Decorator section.
Methods associated with decorators include:
- 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)
Zend_Form_Element handles a variety of attributes and element metadata. Basic attributes include:
- 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
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:
- 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:
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.
Zend_Form ships with concrete classes representing the following XHTML elements:
- 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
You can create your own custom elements by simply extending the Zend_Form_Element class. Common reasons to do so include:
- Elements that share common validators and/or filters
- Elements that have custom decorator functionality
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:
You could then inform your form object about the prefix path for such elements, and start creating elements:
The 'foo' element will now be of type My_Element_Text, and exhibit the behaviour you've outlined.
There are many ways to customize elements; be sure to read the API documentation of Zend_Form_Element to know all the methods available.