Previous Next

Creating Form Elements Using Zend_Form_Element

A form is made of elements that 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 prior to validation and/or 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. Additionally, Zend Framework ships with a number of standard XHTML elements; you can read about them in the Standard Elements chapter.

Plugin Loaders

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 to encapsulate custom functionality.

Example #1 Custom Label

One common use case for plugins is to provide replacements for standard classes. For instance, if you want to provide a different implementation of the 'Label' decorator -- for instance, to always append a colon -- you could create your own 'Label' decorator with your own class prefix, and then add it to your prefix path.

Let's start with a custom Label decorator. We'll give it the class prefix "My_Decorator", and the class itself will be in the file "My/Decorator/Label.php".

class My_Decorator_Label extends Zend_Form_Decorator_Abstract
{
    protected $_placement = 'PREPEND';

    public function render($content)
    {
        if (null === ($element = $this->getElement())) {
            return $content;
        }
        if (!method_exists($element, 'getLabel')) {
            return $content;
        }

        $label = $element->getLabel() . ':';

        if (null === ($view = $element->getView())) {
            return $this->renderLabel($content, $label);
        }

        $label = $view->formLabel($element->getName(), $label);

        return $this->renderLabel($content, $label);
    }

    public function renderLabel($content, $label)
    {
        $placement = $this->getPlacement();
        $separator = $this->getSeparator();

        switch ($placement) {
            case 'APPEND':
                return $content . $separator . $label;
            case 'PREPEND':
            default:
                return $label . $separator . $content;
        }
    }
}

Now we can tell the element to use this plugin path when looking for decorators:

$element->addPrefixPath('My_Decorator', 'My/Decorator/', 'decorator');

Alternately, we can do that at the form level to ensure all decorators use this path:

$form->addElementPrefixPath('My_Decorator', 'My/Decorator/', 'decorator');

After it added as in the example above, the 'My/Decorator/' path will be searched first to see if the decorator exists there when you add a decorator. As a result, 'My_Decorator_Label' will now be used when the 'Label' decorator is requested.

Filters

It's often useful and/or necessary to perform some normalization on input prior to validation. For example, you may want to strip out all HTML, but run your validations on what remains to ensure the submission is valid. Or you may want to trim empty space surrounding input so that a StringLength validator will use the correct length of the input without counting leading or trailing whitespace characters. These operations may be performed using Zend_Filter. Zend_Form_Element has support for filter chains, allowing you to specify multiple, sequential filters. Filtering happens both during validation and when you retrieve the element value via getValue():

$filtered = $element->getValue();

Filters may be added to the chain in two ways:

  • passing in a concrete filter instance

  • providing a short filter name

Let's see some examples:

// Concrete filter instance:
$element->addFilter(new Zend_Filter_Alnum());

// Short filter name:
$element->addFilter('Alnum');
$element->addFilter('alnum');

Short names are typically the filter name minus the prefix. In the default case, this will mean minus the 'Zend_Filter_' prefix. The first letter can be upper-cased or lower-cased.

Note: 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 filters under the 'My_Filter' prefix, you can tell Zend_Form_Element about this as follows:

$element->addPrefixPath('My_Filter', 'My/Filter/', 'filter');

(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:

$unfiltered = $element->getUnfilteredValue();

For more information on filters, see the Zend_Filter documentation.

Methods associated with filters include:

  • addFilter($nameOfFilter, 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)

Validators

If you subscribe to the security mantra of "filter input, escape output," you'll should use validator to filter input submitted with your form. 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 short validator name

Let's see some examples:

// Concrete validator instance:
$element->addValidator(new Zend_Validate_Alnum());

// Short validator name:
$element->addValidator('Alnum');
$element->addValidator('alnum');

Short names are typically the validator name minus the prefix. In the default case, this will mean minus the 'Zend_Validate_' prefix. As is the case with filters, the first letter can be upper-cased or lower-cased.

Note: 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:

$element->addPrefixPath('My_Validator', 'My/Validator/', 'validate');

(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:

$element->addValidator('alnum', true);

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:

$element->addValidator('StringLength', false, array(6, 20));

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:

$validator = new Zend_Validate_StringLength(6, 20);

Note: Providing Custom Validator Error Messages

Some developers may wish to provide custom error messages for a validator. The $options argument of the Zend_Form_Element::addValidator() method allows you to do so by providing the key 'messages' and mapping it to an array of key/value pairs for setting the message templates. You will need to know the error codes of the various validation error types for the particular validator.

A better option is to use a Zend_Translate_Adapter with your form. Error codes are automatically passed to the adapter by the default Errors decorator; you can then specify your own error message strings by setting up translations for the various error codes of your validators.

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():

$element->addValidators(array(
    array('NotEmpty', true),
    array('alnum'),
    array('stringLength', false, array(6, 20)),
));

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

$element->addValidators(array(
    array(
        'validator'           => 'NotEmpty',
        'breakChainOnFailure' => true),
    array('validator' => 'alnum'),
    array(
        'validator' => 'stringLength',
        'options'   => array(6, 20)),
));

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

element.validators.notempty.validator = "NotEmpty"
element.validators.notempty.breakChainOnFailure = true
element.validators.alnum.validator = "Alnum"
element.validators.strlen.validator = "StringLength"
element.validators.strlen.options.min = 6
element.validators.strlen.options.max = 20

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 isValid():

if ($element->isValid($value)) {
    // valid
} else {
    // invalid
}

Note: Validation Operates On Filtered Values

Zend_Form_Element::isValid() filters values through the provided filter chain prior to validation. See the Filters section for more information.

Note: Validation Context

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:

class My_Validate_PasswordConfirmation extends Zend_Validate_Abstract
{
    const NOT_MATCH = 'notMatch';

    protected $_messageTemplates = array(
        self::NOT_MATCH => 'Password confirmation does not match'
    );

    public function isValid($value, $context = null)
    {
        $value = (string) $value;
        $this->_setValue($value);

        if (is_array($context)) {
            if (isset($context['password_confirm'])
                && ($value == $context['password_confirm']))
            {
                return true;
            }
        } elseif (is_string($context) && ($value == $context)) {
            return true;
        }

        $this->_error(self::NOT_MATCH);
        return false;
    }
}

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:

$errors   = $element->getErrors();
$messages = $element->getMessages();

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

In addition to validators, you can specify that an element is required, using setRequired($flag). By default, this flag is FALSE. In combination with setAllowEmpty($flag) (TRUE by default) and setAutoInsertNotEmptyValidator($flag) (TRUE by default), the behavior of your validator chain can be modified in a number of ways:

  • Using the defaults, validating an Element without passing a value, or passing an empty string for it, skips all validators and validates to TRUE.

  • setAllowEmpty(false) leaving the two other mentioned flags untouched, will validate against the validator chain you defined for this Element, regardless of the value passed to isValid().

  • setRequired(true) leaving the two other mentioned flags untouched, will add a 'NotEmpty' validator on top of the validator chain (if none was already set)), with the $breakChainOnFailure flag set. This behavior lends required flag semantic meaning: if no value is passed, we immediately invalidate the submission and notify the user, and prevent other validators from running on what we already know is invalid data.

    If you do not want this behavior, you can turn it off by passing a FALSE value to setAutoInsertNotEmptyValidator($flag); this will prevent isValid() from placing the 'NotEmpty' validator in the validator chain.

For more information on validators, see the Zend_Validate documentation.

Note: Using Zend_Form_Elements as general-purpose validators

Zend_Form_Element implements Zend_Validate_Interface, meaning an element may also be used as a validator in other, non-form related validation chains.

Note: When is an element detected as empty?

As mentioned the 'NotEmpty' validator is used to detect if an element is empty or not. But Zend_Validate_NotEmpty does, per default, not work like PHP's method empty().

This means when an element contains an integer 0 or an string '0' then the element will be seen as not empty. If you want to have a different behaviour you must create your own instance of Zend_Validate_NotEmpty. There you can define the behaviour of this validator. See » Zend_Validate_NotEmpty for details.

Methods associated with validation include:

  • setRequired($flag) and isRequired() allow you to set and retrieve the status of the 'required' flag. When set to boolean TRUE, this flag requires that the element be in the data processed by Zend_Form.

  • setAllowEmpty($flag) and getAllowEmpty() allow you to modify the behaviour of optional elements (i.e., elements where the required flag is FALSE). When the 'allow empty' flag is TRUE, empty values will not be passed to the validator chain.

  • setAutoInsertNotEmptyValidator($flag) allows you to specify whether or not a 'NotEmpty' validator will be prepended to the validator chain when the element is required. By default, this flag is TRUE.

  • 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)

Custom Error Messages

At times, you may want to specify one or more specific error messages to use instead of the error messages generated by the validators attached to your element. Additionally, at times you may want to mark the element invalid yourself. As of 1.6.0, this functionality is possible via the following methods.

  • addErrorMessage($message): add an error message to display on form validation errors. You may call this more than once, and new messages are appended to the stack.

  • addErrorMessages(array $messages): add multiple error messages to display on form validation errors.

  • setErrorMessages(array $messages): add multiple error messages to display on form validation errors, overwriting all previously set error messages.

  • getErrorMessages(): retrieve the list of custom error messages that have been defined.

  • clearErrorMessages(): remove all custom error messages that have been defined.

  • markAsError(): mark the element as having failed validation.

  • hasErrors(): determine whether the element has either failed validation or been marked as invalid.

  • addError($message): add a message to the custom error messages stack and flag the element as invalid.

  • addErrors(array $messages): add several messages to the custom error messages stack and flag the element as invalid.

  • setErrors(array $messages): overwrite the custom error messages stack with the provided messages and flag the element as invalid.

All errors set in this fashion may be translated. Additionally, you may insert the placeholder "%value%" to represent the element value; this current element value will be substituted when the error messages are retrieved.

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 special 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. The 'helper' element attribute can be used to specify which view helper to use. By default, Zend_Form_Element specifies the 'formText' view helper, but individual subclasses specify different helpers.

  • Errors: appends error messages to the element using Zend_View_Helper_FormErrors. If none are present, nothing is appended.

  • Description: appends the element description. If none is present, nothing is appended. By default, the description is rendered in a <p> tag with a class of 'description'.

  • HtmlTag: wraps the element and errors in an HTML <dd> tag.

  • Label: prepends a label to the element using Zend_View_Helper_FormLabel, and wraps it in a <dt> tag. If no label is provided, just the definition term tag is rendered.

Note: Default Decorators Do Not Need to Be Loaded

By default, the default decorators are loaded during object initialization. You can disable this by passing the 'disableLoadDefaultDecorators' option to the constructor:

$element = new Zend_Form_Element('foo',
                                 array('disableLoadDefaultDecorators' =>
                                      true)
                                );

This option may be mixed with any other options you pass, both as array options or in a Zend_Config object.

Since the order in which decorators are registered matters- the 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:

$this->addDecorators(array(
    array('ViewHelper'),
    array('Errors'),
    array('Description', array('tag' => 'p', 'class' => 'description')),
    array('HtmlTag', array('tag' => 'dd')),
    array('Label', array('tag' => 'dt')),
));

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. If a description is present, the 'Description' decorator will append a paragraph of class 'description' containing the descriptive text to the aggregated content. The next decorator, 'HtmlTag', wraps the element, errors, and description in an HTML <dd> tag. Finally, the last decorator, 'label', retrieves the element's label and passes it to the 'FormLabel' view helper, wrapping it in an HTML <dt> tag; the value is prepended to the content by default. The resulting output looks basically like this:

  • "123" is not an alphanumeric value

This is some descriptive text regarding the element.

For more information on decorators, read the Zend_Form_Decorator section.

Note: Using Multiple Decorators of the Same Type

Internally, Zend_Form_Element uses a decorator's class as the lookup mechanism when retrieving decorators. As a result, you cannot register multiple decorators of the same type; subsequent decorators will simply overwrite those that existed before.

To get around this, you can use aliases. Instead of passing a decorator or decorator name as the first argument to addDecorator(), pass an array with a single element, with the alias pointing to the decorator object or name:

// Alias to 'FooBar':
$element->addDecorator(array('FooBar' => 'HtmlTag'),
                       array('tag' => 'div'));

// And retrieve later:
$decorator = $element->getDecorator('FooBar');

In the addDecorators() and setDecorators() methods, you will need to pass the 'decorator' option in the array representing the decorator:

// Add two 'HtmlTag' decorators, aliasing one to 'FooBar':
$element->addDecorators(
    array('HtmlTag', array('tag' => 'div')),
    array(
        'decorator' => array('FooBar' => 'HtmlTag'),
        'options' => array('tag' => 'dd')
    ),
);

// And retrieve later:
$htmlTag = $element->getDecorator('HtmlTag');
$fooBar  = $element->getDecorator('FooBar');

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 also uses overloading to allow rendering specific decorators. __call() will intercept methods that lead with the text 'render' and use the remainder of the method name to lookup a decorator; if found, it will then render that single decorator. Any arguments passed to the method call will be used as content to pass to the decorator's render() method. As an example:

// Render only the ViewHelper decorator:
echo $element->renderViewHelper();

// Render only the HtmlTag decorator, passing in content:
echo $element->renderHtmlTag("This is the html tag content");

If the decorator does not exist, an exception is raised.

Metadata and Attributes

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.

  • description: a description of the element; often used to provide tooltip or javascript contextual hinting describing the purpose of the element. Uses the setDescription() and getDescription() accessors.

  • required: flag indicating whether or not the element is required when performing form validation. Uses the setRequired() and getRequired() accessors. This flag is FALSE by default.

  • allowEmpty: flag indicating whether or not a non-required (optional) element should attempt to validate empty values. If it is set to TRUE and the required flag is FALSE, empty values are not passed to the validator chain and are presumed TRUE. Uses the setAllowEmpty() and getAllowEmpty() accessors. This flag is TRUE by default.

  • autoInsertNotEmptyValidator: flag indicating whether or not to insert a 'NotEmpty' validator when the element is required. By default, this flag is TRUE. Set the flag with setAutoInsertNotEmptyValidator($flag) and determine the value with autoInsertNotEmptyValidator().

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

  • setAttribs(array $attribs): like addAttribs(), but overwrites

  • getAttrib($name): retrieve a single attribute value

  • getAttribs(): retrieve all attributes as key/value pairs

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

// Equivalent to $element->setAttrib('class', 'text'):
$element->class = 'text;

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.

Standard Elements

Zend_Form ships with a number of standard elements; please read the Standard Elements chapter for full details.

Zend_Form_Element Methods

Zend_Form_Element has many, many methods. What follows is a quick summary of their signatures, grouped by type:

  • Configuration:

    • setOptions(array $options)

    • setConfig(Zend_Config $config)

  • I18n:

    • setTranslator(Zend_Translate_Adapter $translator = null)

    • getTranslator()

    • setDisableTranslator($flag)

    • translatorIsDisabled()

  • Properties:

    • setName($name)

    • getName()

    • setValue($value)

    • getValue()

    • getUnfilteredValue()

    • setLabel($label)

    • getLabel()

    • setDescription($description)

    • getDescription()

    • setOrder($order)

    • getOrder()

    • setRequired($flag)

    • getRequired()

    • setAllowEmpty($flag)

    • getAllowEmpty()

    • setAutoInsertNotEmptyValidator($flag)

    • autoInsertNotEmptyValidator()

    • setIgnore($flag)

    • getIgnore()

    • 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)

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.

Exceptions to the rule include the following:

  • 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

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

[element]
name = "foo"
value = "foobar"
label = "Foo:"
order = 10
required = true
allowEmpty = false
autoInsertNotEmptyValidator = true
description = "Foo elements are for examples"
ignore = false
attribs.id = "foo"
attribs.class = "element"
; sets 'onclick' attribute
onclick = "autoComplete(this, '/form/autocomplete/element')"
prefixPaths.decorator.prefix = "My_Decorator"
prefixPaths.decorator.path = "My/Decorator/"
disableTranslator = 0
validators.required.validator = "NotEmpty"
validators.required.breakChainOnFailure = true
validators.alpha.validator = "alpha"
validators.regex.validator = "regex"
validators.regex.options.pattern = "/^[A-F].*/$"
filters.ucase.filter = "StringToUpper"
decorators.element.decorator = "ViewHelper"
decorators.element.options.helper = "FormText"
decorators.label.decorator = "Label"

Custom Elements

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

There are two methods typically used to extend an element: init(), which can be used to add custom initialization logic to your element, and loadDefaultDecorators(), which can be used to set a list of default decorators used by your element.

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'. In addition, you have a number of standard attributes, including 'size', 'maxLength', and 'class' you wish to specify. You could define an element to accomplish this as follows:

class My_Element_Text extends Zend_Form_Element
{
    public function init()
    {
        $this->addPrefixPath('My_Decorator', 'My/Decorator/', 'decorator')
             ->addFilters('StringTrim')
             ->addValidator('Regex', false, array('/^[a-z0-9]{6,}$/i'))
             ->addDecorator('TextItem')
             ->setAttrib('size', 30)
             ->setAttrib('maxLength', 45)
             ->setAttrib('class', 'text');
    }
}

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

$form->addPrefixPath('My_Element', 'My/Element/', 'element')
     ->addElement('text', 'foo');

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

Another method you may want to override when extending Zend_Form_Element is the loadDefaultDecorators() method. This method conditionally loads a set of default decorators for your element; you may wish to substitute your own decorators in your extending class:

class My_Element_Text extends Zend_Form_Element
{
    public function loadDefaultDecorators()
    {
        $this->addDecorator('ViewHelper')
             ->addDecorator('DisplayError')
             ->addDecorator('Label')
             ->addDecorator('HtmlTag',
                            array('tag' => 'div', 'class' => 'element'));
    }
}

There are many ways to customize elements. Read the API documentation of Zend_Form_Element to learn about all of the available methods.

Previous Next
Introduction to Zend Framework
Overview
Installation
Learning Zend Framework
Zend Framework Quick Start
Zend Framework & MVC Introduction
Create Your Project
Create A Layout
Create a Model and Database Table
Create A Form
Congratulations!
Autoloading in Zend Framework
Introduction
Goals and Design
Basic Autoloader Usage
Resource Autoloading
Conclusion
Plugins in Zend Framework
Introduction
Using Plugins
Conclusion
Getting Started with Zend_Layout
Introduction
Using Zend_Layout
Zend_Layout: Conclusions
Getting Started Zend_View Placeholders
Introduction
Basic Placeholder Usage
Standard Placeholders
View Placeholders: Conclusion
Understanding and Using Zend Form Decorators
Introduction
Decorator Basics
Layering Decorators
Rendering Individual Decorators
Creating and Rendering Composite Elements
Conclusion
Getting Started with Zend_Session, Zend_Auth, and Zend_Acl
Building Multi-User Applications With Zend Framework
Managing User Sessions In ZF
Authenticating Users in Zend Framework
Building an Authorization System in Zend Framework
Getting Started with Zend_Search_Lucene
Zend_Search_Lucene Introduction
Lucene Index Structure
Index Opening and Creation
Indexing
Searching
Supported queries
Search result pagination
Getting Started with Zend_Paginator
Introduction
Simple Examples
Pagination Control and ScrollingStyles
Putting it all Together
Zend Framework Reference
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Application
Introduction
Zend_Application Quick Start
Theory of Operation
Examples
Core Functionality
Available Resource Plugins
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Barcode
Introduction
Barcode creation using Zend_Barcode class
Zend_Barcode Objects
Zend_Barcode Renderers
Zend_Cache
Introduction
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
The Cache Manager
Zend_Captcha
Introduction
Captcha Operation
CAPTCHA Adapters
Zend_CodeGenerator
Introduction
Zend_CodeGenerator Examples
Zend_CodeGenerator Reference
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Zend_Controller Quick Start
Zend_Controller Basics
The Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Zend_Currency
Introduction to Zend_Currency
Using Zend_Currency
Options for currencies
What makes a currency?
Where is the currency?
How does the currency look like?
How much is my currency?
Calculating with currencies
Exchanging currencies
Additional informations on Zend_Currency
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of Dates
Constants for General Date Functions
Working Examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Db_Table_Definition
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dojo build layer support
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
Basic usage
Previous Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_Feed_Reader
Zend_Feed_Writer
Zend_Feed_Pubsubhubbub
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Basic Usage
Advanced Usage of Zend_Json
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
API overview
Usage Scenarios
Tools
Object oriented access to the LDAP tree using Zend_Ldap_Node
Getting information from the LDAP server
Serializing LDAP data to and from LDIF
Zend_Loader
Loading Files and Classes Dynamically
The Autoloader
Resource Autoloaders
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Zend_Log
Overview
Writers
Formatters
Filters
Using the Factory to Create a Log
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Markup
Introduction
Getting Started With Zend_Markup
Zend_Markup Parsers
Zend_Markup Renderers
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
Introduction
Pages
Containers
Zend_Oauth
Introduction to OAuth
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction
Creating and Loading PDF Documents
Save Changes to PDF Documents
Working with Pages
Drawing
Interactive Features
Document Info and Metadata
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Queue
Introduction
Example usage
Framework
Adapters
Customizing Zend_Queue
Stomp
Zend_Reflection
Introduction
Zend_Reflection Examples
Zend_Reflection Reference
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Serializer
Introduction
Zend_Serializer_Adapter
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Storage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2: Regions and Availability Zones
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
Zend_Service_Amazon_Sqs
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_DeveloperGarden
Zend_Service_Flickr
Zend_Service_LiveDocx
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Zend_Service_SlideShare
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_WindowsAzure
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Test_PHPUnit_Db
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Tool
Using Zend_Tool On The Command Line
Extending Zend_Tool
Zend_Tool_Framework
Introduction
Using the CLI Tool
Architecture
Creating Providers to use with Zend_Tool_Framework
Shipped System Providers
Extending and Configuring Zend_Tool_Framework
Zend_Tool_Project
Introduction
Create A Project
Zend_Tool Project Providers
Zend_Tool_Project Internals
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Creating source files
Additional features for translation
Plural notations for Translation
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Validation Messages
Zend_Version
Getting the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
ZendX_Console_Process_Unix
ZendX_Console_Process_Unix
ZendX_JQuery
Introduction
ZendX_JQuery View Helpers
ZendX_JQuery Form Elements and Decorators
Zend Framework Requirements
Introduction
Zend Framework Migration Notes
Zend Framework 1.10
Zend Framework 1.9
Zend Framework 1.8
Zend Framework 1.7
Zend Framework 1.6
Zend Framework 1.5
Zend Framework 1.0
Zend Framework 0.9
Zend Framework 0.8
Zend Framework 0.6
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Documentation Standard
Overview
Documentation File Formatting
Recommendations
Recommended Project Structure for Zend Framework MVC Applications
Overview
Recommended Project Directory Structure
Module Structure
Rewrite Configuration Guide
Zend Framework Performance Guide
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information