PhpRiot
Become Zend Certified

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


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

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:

<?php
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:

<?php
$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:

<?php
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.

Zend Framework