Previous Next

Standard Form Elements Shipped With Zend Framework

Zend Framework ships with concrete element classes covering most HTML form elements. Most simply specify a particular view helper for use when decorating the element, but several offer additional functionality. The following is a list of all such classes, as well as descriptions of the functionality they offer.

Zend_Form_Element_Button

Used for creating HTML button elements, Zend_Form_Element_Button extends Zend_Form_Element_Submit, deriving its custom functionality. It specifies the 'formButton' view helper for decoration.

Like the submit element, it uses the element's label as the element value for display purposes; in other words, to set the text of the button, set the value of the element. The label will be translated if a translation adapter is present.

Because the label is used as part of the element, the button element uses only the ViewHelper and DtDdWrapper decorators.

After populating or validating a form, you can check if the given button was clicked using the isChecked() method.

Zend_Form_Element_Captcha

CAPTCHAs are used to prevent automated submission of forms by bots and other automated processes.

The Captcha form element allows you to specify which Zend_Captcha adapter you wish to utilize as a form captcha. It then sets this adapter as a validator to the object, and uses a Captcha decorator for rendering (which proxies to the captcha adapter).

Adapters may be any adapters in Zend_Captcha, as well as any custom adapters you may have defined elsewhere. To allow this, you may pass an additional plugin loader type key, 'CAPTCHA' or 'captcha', when specifying a plugin loader prefix path:

$element->addPrefixPath('My_Captcha', 'My/Captcha/', 'captcha');

Captcha's may then be registered using the setCaptcha() method, which can take either a concrete captcha instance, or the short name of a captcha adapter:

// Concrete instance:
$element->setCaptcha(new Zend_Captcha_Figlet());

// Using shortnames:
$element->setCaptcha('Dumb');

If you wish to load your element via configuration, specify either the key 'captcha' with an array containing the key 'captcha', or both the keys 'captcha' and 'captchaOptions':

// Using single captcha key:
$element = new Zend_Form_Element_Captcha('foo', array(
    'label' => "Please verify you're a human",
    'captcha' => array(
        'captcha' => 'Figlet',
        'wordLen' => 6,
        'timeout' => 300,
    ),
));

// Using both captcha and captchaOptions:
$element = new Zend_Form_Element_Captcha('foo', array(
    'label' => "Please verify you're a human"
    'captcha' => 'Figlet',
    'captchaOptions' => array(
        'captcha' => 'Figlet',
        'wordLen' => 6,
        'timeout' => 300,
    ),
));

The decorator used is determined by querying the captcha adapter. By default, the Captcha decorator is used, but an adapter may specify a different one via its getDecorator() method.

As noted, the captcha adapter itself acts as a validator for the element. Additionally, the NotEmpty validator is not used, and the element is marked as required. In most cases, you should need to do nothing else to have a captcha present in your form.

Zend_Form_Element_Checkbox

HTML checkboxes allow you return a specific value, but basically operate as booleans: when it is checked, the value is submitted; when it's not checked, nothing is submitted. Internally, Zend_Form_Element_Checkbox enforces this state.

By default, the checked value is '1', and the unchecked value '0'. You can specify the values to use using the setCheckedValue() and setUncheckedValue() accessors, respectively. Internally, any time you set the value, if the provided value matches the checked value, then it is set, but any other value causes the unchecked value to be set.

Additionally, setting the value sets the checked property of the checkbox. You can query this using isChecked() or simply accessing the property. Using the setChecked($flag) method will both set the state of the flag as well as set the appropriate checked or unchecked value in the element. Please use this method when setting the checked state of a checkbox element to ensure the value is set properly.

Zend_Form_Element_Checkbox uses the 'formCheckbox' view helper. The checked value is always used to populate it.

Zend_Form_Element_File

The File form element provides a mechanism for supplying file upload fields to your form. It utilizes Zend_File_Transfer internally to provide this functionality, and the FormFile view helper as also the File decorator to display the form element.

By default, it uses the Http transfer adapter, which introspects the $_FILES array and allows you to attach validators and filters. Validators and filters attached to the form element will be attached to the transfer adapter.

Example #1 File form element usage

The above explanation of using the File form element may seem arcane, but actual usage is relatively trivial:

$element = new Zend_Form_Element_File('foo');
$element->setLabel('Upload an image:')
        ->setDestination('/var/www/upload');
// ensure only 1 file
$element->addValidator('Count', false, 1);
// limit to 100K
$element->addValidator('Size', false, 102400);
// only JPEG, PNG, and GIFs
$element->addValidator('Extension', false, 'jpg,png,gif');
$form->addElement($element, 'foo');

You also need to ensure the correct encoding type is provided to the form; you should use 'multipart/form-data'. You can do this by setting the 'enctype' attribute on the form:

$form->setAttrib('enctype', 'multipart/form-data');

When the form has successfully validated, you have to receive the file to store it in the final destination using receive(). Additionally you can determinate the final location using getFileName():

if (!$form->isValid) {
    print "Ohoh... validation error";
}

if (!$form->foo->receive()) {
    print "Error receiving the file";
}

$location = $form->foo->getFileName();

Note: Default upload locations

By default, files are uploaded to the system temp directory.

Note: File values

Within HTTP a file element has no value. Therefor and because of security reasons you will only get the uploaded filename by calling getValue() and not the complete path. If you need the full informations call getFileName()you will return you path and name of the file.

There are several states of the uploaded file which can be checked with the following methods:

  • isUploaded(): Checks if the file element has been uploaded or not.

  • isReceived(): Checks if the file element has already been received.

  • isFiltered(): Checks if the filters have already been applied to the file element or not.

Example #2 Checking if an optional file has been uploaded

$element = new Zend_Form_Element_File('foo');
$element->setLabel('Upload an image:')
        ->setDestination('/var/www/upload')
        ->setRequired(false);
$element->addValidator('Size', false, 102400);
$form->addElement($element, 'foo');

// The foo file element is optional but when it's given go into here
if ($form->foo->isUploaded()) {
    // foo file given... do something
}

Zend_Form_Element_File supports also multiple files. By calling the setMultiFile($count) method you can set the ammount of file elements you want to create. This prevents you from setting the same settings multiple times.

Example #3 Setting multiple files

Creating a multifile element is the same like setting a single element. Just call setMultiFile() additionally after creation:

$element = new Zend_Form_Element_File('foo');
$element->setLabel('Upload an image:')
        ->setDestination('/var/www/upload');
// ensure minimum 1, maximum 3 files
$element->addValidator('Count', false, array('min' => 1, 'max' => 3));
// limit to 100K
$element->addValidator('Size', false, 102400);
// only JPEG, PNG, and GIFs
$element->addValidator('Extension', false, 'jpg,png,gif');
// defines 3 identical file elements
$element->setMultiFile(3);
$form->addElement($element, 'foo');

In your view you will now get 3 identical file upload elements which all share the same settings. To get the set multifile number simply call getMultiFile().

Note: File elements in Subforms

When you use file elements in subforms you must set unique names. So when you named you file element in subform1 "file", you must give it a different name in subform2.

As soon as there are 2 identical named file elements, the second element would not be displayed or submitted.

To limit the size of the file, which is uploaded by the client, you should additionally set the maximum file size the form accepts. This will limit the size on the client side by setting the MAX_FILE_SIZE option on the form. As soon as you set this value by using the setMaxFileSize($size) method, it will be rendered with the file element.

$element = new Zend_Form_Element_File('foo');
$element->setLabel('Upload an image:')
        ->setDestination('/var/www/upload')
        ->addValidator('Size', false, 102400) // limit to 100K
        ->setMaxFileSize(102400); // limits the filesize on the client side
$form->addElement($element, 'foo');

Note: MaxFileSize with multiple file elements

When you use multiple file elements in your form you will have to set the MAX_FILE_SIZE only once. Setting it again will overwrite the previous set value.

Note, that you can set MAX_FILE_SIZE only once, even if you use multiple forms.

Zend_Form_Element_Hidden

Hidden elements merely inject data that should be submitted, but which the user should not manipulate. Zend_Form_Element_Hidden accomplishes this through use of the 'formHidden' view helper.

Zend_Form_Element_Hash

This element provides protection from CSRF attacks on forms, ensuring the data is submitted by the user session that generated the form and not by a rogue script. Protection is achieved by adding a hash element to a form and verifying it when the form is submitted.

The name of the hash element should be unique. It is recommended to use the salt option for the element, two hashes with same names and different salts would not collide:

$form->addElement('hash', 'no_csrf_foo', array('salt' => 'unique'));

You can set the salt later using the setSalt($salt) method.

Internally, the element stores a unique identifier using Zend_Session_Namespace, and checks for it at submission (checking that the TTL has not expired). The 'Identical' validator is then used to ensure the submitted hash matches the stored hash.

The 'formHidden' view helper is used to render the element in the form.

Zend_Form_Element_Image

Images can be used as form elements, and allow you to specify graphical elements as form buttons.

Images need an image source. Zend_Form_Element_Image allows you to specify this by using the setImage() accessor (or 'image' configuration key). You can also optionally specify a value to use when submitting the image using the setImageValue() accessor (or 'imageValue' configuration key). When the value set for the element matches the imageValue, then the accessor isChecked() will return true.

The Image element uses the Image Decorator for rendering (as well as the standard Errors, HtmlTag, and Label decorators). You can optionally specify a tag to the Image decorator that will then wrap the image element.

Zend_Form_Element_MultiCheckbox

Often you have a set of related checkboxes, and you wish to group the results. This is much like a Multiselect, but instead of them being in a dropdown list, you need to show checkbox/value pairs.

Zend_Form_Element_MultiCheckbox makes this a snap. Like all other elements extending the base Multi element, you can specify a list of options, and easily validate against that same list. The 'formMultiCheckbox' view helper ensures that these are returned as an array in the form submission.

By default, this element registers an InArray validator which validates against the array keys of registered options. You can disable this behavior by either calling setRegisterInArrayValidator(false), or by passing a false value to the registerInArrayValidator configuration key.

You may manipulate the various checkbox options using the following methods:

  • addMultiOption($option, $value)

  • addMultiOptions(array $options)

  • setMultiOptions(array $options) (overwrites existing options)

  • getMultiOption($option)

  • getMultiOptions()

  • removeMultiOption($option)

  • clearMultiOptions()

To mark checked items, you need to pass an array of values to setValue(). The following will check the values "bar" and "bat":

$element = new Zend_Form_Element_MultiCheckbox('foo', array(
    'multiOptions' => array(
        'foo' => 'Foo Option',
        'bar' => 'Bar Option',
        'baz' => 'Baz Option',
        'bat' => 'Bat Option',
    );
));

$element->setValue(array('bar', 'bat'));

Note that even when setting a single value, you must pass an array.

Zend_Form_Element_Multiselect

XHTML select elements allow a 'multiple' attribute, indicating multiple options may be selected for submission, instead of the usual one. Zend_Form_Element_Multiselect extends Zend_Form_Element_Select, and sets the multiple attribute to 'multiple'. Like other classes that inherit from the base Zend_Form_Element_Multi class, you can manipulate the options for the select using:

  • addMultiOption($option, $value)

  • addMultiOptions(array $options)

  • setMultiOptions(array $options) (overwrites existing options)

  • getMultiOption($option)

  • getMultiOptions()

  • removeMultiOption($option)

  • clearMultiOptions()

If a translation adapter is registered with the form and/or element, option values will be translated for display purposes.

By default, this element registers an InArray validator which validates against the array keys of registered options. You can disable this behavior by either calling setRegisterInArrayValidator(false), or by passing a false value to the registerInArrayValidator configuration key.

Zend_Form_Element_Password

Password elements are basically normal text elements -- except that you typically do not want the submitted password displayed in error messages or the element itself when the form is re-displayed.

Zend_Form_Element_Password achieves this by calling setObscureValue(true) on each validator (ensuring that the password is obscured in validation error messages), and using the 'formPassword' view helper (which does not display the value passed to it).

Zend_Form_Element_Radio

Radio elements allow you to specify several options, of which you need a single value returned. Zend_Form_Element_Radio extends the base Zend_Form_Element_Multi class, allowing you to specify a number of options, and then uses the formRadio view helper to display these.

By default, this element registers an InArray validator which validates against the array keys of registered options. You can disable this behavior by either calling setRegisterInArrayValidator(false), or by passing a false value to the registerInArrayValidator configuration key.

Like all elements extending the Multi element base class, the following methods may be used to manipulate the radio options displayed:

  • addMultiOption($option, $value)

  • addMultiOptions(array $options)

  • setMultiOptions(array $options) (overwrites existing options)

  • getMultiOption($option)

  • getMultiOptions()

  • removeMultiOption($option)

  • clearMultiOptions()

Zend_Form_Element_Reset

Reset buttons are typically used to clear a form, and are not part of submitted data. However, as they serve a purpose in the display, they are included in the standard elements.

Zend_Form_Element_Reset extends Zend_Form_Element_Submit. As such, the label is used for the button display, and will be translated if a translation adapter is present. It utilizes only the 'ViewHelper' and 'DtDdWrapper' decorators, as there should never be error messages for such elements, nor will a label be necessary.

Zend_Form_Element_Select

Select boxes are a common way of limiting to specific choices for a given form datum. Zend_Form_Element_Select allows you to generate these quickly and easily.

By default, this element registers an InArray validator which validates against the array keys of registered options. You can disable this behavior by either calling setRegisterInArrayValidator(false), or by passing a false value to the registerInArrayValidator configuration key.

As it extends the base Multi element, the following methods may be used to manipulate the select options:

  • addMultiOption($option, $value)

  • addMultiOptions(array $options)

  • setMultiOptions(array $options) (overwrites existing options)

  • getMultiOption($option)

  • getMultiOptions()

  • removeMultiOption($option)

  • clearMultiOptions()

Zend_Form_Element_Select uses the 'formSelect' view helper for decoration.

Zend_Form_Element_Submit

Submit buttons are used to submit a form. You may use multiple submit buttons; you can use the button used to submit the form to decide what action to take with the data submitted. Zend_Form_Element_Submit makes this decisioning easy, by adding a isChecked() method; as only one button element will be submitted by the form, after populating or validating the form, you can call this method on each submit button to determine which one was used.

Zend_Form_Element_Submit uses the label as the "value" of the submit button, translating it if a translation adapter is present. isChecked() checks the submitted value against the label in order to determine if the button was used.

The ViewHelper and DtDdWrapper decorators to render the element. No label decorator is used, as the button label is used when rendering the element; also, typically, you will not associate errors with a submit element.

Zend_Form_Element_Text

By far the most prevalent type of form element is the text element, allowing for limited text entry; it's an ideal element for most data entry. Zend_Form_Element_Text simply uses the 'formText' view helper to display the element.

Zend_Form_Element_Textarea

Textareas are used when large quantities of text are expected, and place no limits on the amount of text submitted (other than maximum size limits as dictated by your server or PHP). Zend_Form_Element_Textarea uses the 'textArea' view helper to display such elements, placing the value as the content of the element.

Previous Next
Introduction to Zend Framework
Overview
Installation
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Cache
Introduction
The theory of caching
Zend_Cache frontends
Zend_Cache backends
Zend_Captcha
Introduction
Captcha Operation
Captcha Adapters
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction to Getopt
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
Migrating from Previous Versions
Zend_Currency
Introduction to Zend_Currency
How to work with currencies
Migrating from Previous Versions
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_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using 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_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Migrating from previous versions
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 to Gdata
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
Zend_Http_Client - 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
JSON Objects
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
Zend_Loader
Loading Files and Classes Dynamically
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Migrating from previous versions
Zend_Log
Overview
Writers
Formatters
Filters
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_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_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 the PDF document.
Document pages.
Drawing
Document Info and Metadata.
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
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_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Introduction
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
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_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Migrating from previous versions
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Zend_Version
Reading 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
Zend Framework Requirements
PHP Version
PHP Extensions
Zend Framework Components
Zend Framework Dependencies
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Performance Guide
Introduction
Class Loading
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information