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

Elements

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

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.

Some examples:

<?php
// Using an element instance:
$element = new Zend_Form_Element_Text('foo');
$form->addElement($element);

// Using a factory
//
// Creates an element of type Zend_Form_Element_Text with the
// name of 'foo':
$form->addElement('text''foo');

// Pass label option to the element:
$form->addElement('text''foo', array('label' => 'Foo:'));

addElement() Implements Fluent Interface

addElement() implements a fluent interface; that is to say, it returns the Zend_Form object, and not the element. This is done to allow you to chain together multiple addElement() methods or other form methods that implement the fluent interface (all setters in Zend_Form implement the pattern).

If you wish to return the element instead, use createElement(), which is outlined below. Be aware, however, that createElement() does not attach the element to the form.

Internally, addElement() actually uses createElement() to create the element before attaching it to the form.

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:

<?php
// getElement():
$foo $form->getElement('foo');

// As object property:
$foo $form->foo;

Occasionally, you may want to create an element without attaching it to the form (for instance, if you wish to make use of the various plugin paths registered with the form, but wish to later attach the object to a sub form). The createElement() method allows you to do so:

<?php
// $username becomes a Zend_Form_Element_Text object:
$username $form->createElement('text''username');

Populating and Retrieving Values

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:

<?php
// Get all values:
$values $form->getValues();

// Get only 'foo' element's value:
$value $form->getValue('foo');

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

<?php
$form
->setDefaults($data);
$form->populate($data);

On the flip side, you may want to clear a form after populating or validating it; this can be done using the reset() method:

<?php
$form
->reset();

Global Operations

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:

Example 442. Setting Prefix Paths for All Elements

You can set prefix paths for all elements by type, or using a global prefix. Some examples:

<?php
// Set global prefix path:
// Creates paths for prefixes My_Foo_Filter, My_Foo_Validate,
// and My_Foo_Decorator
$form->addElementPrefixPath('My_Foo''My/Foo/');

// Just filter paths:
$form->addElementPrefixPath('My_Foo_Filter',
                            
'My/Foo/Filter',
                            
'filter');

// Just validator paths:
$form->addElementPrefixPath('My_Foo_Validate',
                            
'My/Foo/Validate',
                            
'validate');

// Just decorator paths:
$form->addElementPrefixPath('My_Foo_Decorator',
                            
'My/Foo/Decorator',
                            
'decorator');

Example 443. Setting Decorators for All Elements

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:

<?php
$form
->setElementDecorators(array(
    
'ViewHelper',
    
'Label'
));

Example 444. Setting Decorators for Some Elements

You can also set decorators for a subset of elements, either by inclusion or exclusion. The second argument to setElementDecorators() may be an array of element names; by default, specifying such an array will set the specified decorators on those elements only. You may also pass a third argument, a flag indicating whether this list of elements is for inclusion or exclusion purposes. If the flag is FALSE, it will decorate all elements except those in the passed list. As with standard usage of the method, any decorators passed will overwrite any previously set decorators in each element.

In the following snippet, we indicate that we want only the ViewHelper and Label decorators for the 'foo' and 'bar' elements:

<?php
$form
->setElementDecorators(
    array(
        
'ViewHelper',
        
'Label'
    
),
    array(
        
'foo',
        
'bar'
    
)
);

On the flip side, with this snippet, we'll now indicate that we want to use only the ViewHelper and Label decorators for every element except the 'foo' and 'bar' elements:

<?php
$form
->setElementDecorators(
    array(
        
'ViewHelper',
        
'Label'
    
),
    array(
        
'foo',
        
'bar'
    
),
    
false
);

Some Decorators are Inappropriate for Some Elements

While setElementDecorators() may seem like a good solution, there are some cases where it may actually end up with unexpected results. For example, the various button elements (Submit, Button, Reset) currently use the label as the value of the button, and only use ViewHelper and DtDdWrapper decorators -- preventing an additional labels, errors, and hints from being rendered. The example above would duplicate some content (the label) for button elements.

You can use the inclusion/exclusion array to overcome this issue as noted in the previous example.

So, use this method wisely, and realize that you may need to exclude some elements or manually change some elements' decorators to prevent unwanted output.

Example 445. Setting Filters for All Elements

In some cases, you may want to apply the same filter to all elements; a common case is to trim() all values:

<?php
$form
->setElementFilters(array('StringTrim'));

Methods For Interacting With Elements

The following methods may be used to interact with elements:

  • createElement($element, $name = null, $options = null)

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

Zend Framework