Caution: The documentation you are viewing is
for an older version of Zend Framework.
You can find the documentation of the current version at:
https://docs.zendframework.com/
Standard Form Elements Shipped With Zend Framework - Zend_Form
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.
Used for creating HTML button elements, Zend_Form_Element_Button extends Zend_Form_Element_Submit, specifying some 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.
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:
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:
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':
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.
HTML checkboxes allow you return a specific value, but basically operate as booleans. When checked, the checkbox's value is submitted. When the checkbox is 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.
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 are in turn 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:
You also need to ensure that 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:
After the form is validated successfully, you must receive the file to store it in the final destination using receive(). Additionally you can determinate the final location using getFileName():
Note: Default Upload Location
By default, files are uploaded to the system temp directory.
Note: File values
Within HTTP a file element has no value. For this reason and because of security concerns getValue() returns only the uploaded filename and not the complete path. If you need the file path, call getFileName(), which returns both the path and the name of the file.
Note: Return value of getFileName()
The result returned by the getFileName() method will change depending on how many files the Zend_Form_Element_File uploaded:
A single file: string containing the single file name.
Multiple files: an array, where each item is a string containing a single file name.
No files: an empty array
Per default the file will automatically be received when you call getValues() on the form. The reason behind this behaviour is, that the file itself is the value of the file element.
Note: Therefor another call of receive() after calling getValues() will not have an effect. Also creating a instance of Zend_File_Transfer will not have an effect as there no file anymore to receive.
Still, sometimes you may want to call getValues() without receiving the file. You can archive this by calling setValueDisabled(true). To get the actual value of this flag you can call isValueDisabled().
Example #2 Explicit file retrievement
First call setValueDisabled(true).
Now the file will not be received when you call getValues(). So you must call receive() on the file element, or an instance of Zend_File_Transfer yourself.
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 #3 Checking if an optional file has been uploaded
Zend_Form_Element_File also supports multiple files. By calling the setMultiFile($count) method you can set the number of file elements you want to create. This keeps you from setting the same settings multiple times.
Example #4 Setting multiple files
Creating a multifile element is the same as setting a single element. Just call setMultiFile() after the element is created:
You now have 3 identical file upload elements with 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. For example, if you name a file element in subform1 "file", you must give any file element in subform2 a different name.
If there are 2 file elements with the same name, the second element is not be displayed or submitted.
Additionally, file elements are not rendered within the sub-form. So when you add a file element into a subform, then the element will be rendered within the main form.
To limit the size of the file uploaded, you can specify the maximum file size by setting the MAX_FILE_SIZE option on the form. When you set this value by using the setMaxFileSize($size) method, it will be rendered with the file element.
Note: MaxFileSize with Multiple File Elements
When you use multiple file elements in your form you should set the MAX_FILE_SIZE only once. Setting it again will overwrite the previous value.
Note, that this is also the case when you use multiple forms.
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. We recommend using the salt option for the element- two hashes with same names and different salts would not collide:
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.
Note: Testing forms containing Zend_Form_Element_Hash
When unit testing a form containing a Zend_Form_Element_Hash it is necessary to call initCsrfToken and initCsrfValidator before attempting to validate the form. The hash value of the Zend_Form_Element_Hash element must also be injected into the array of values passed as the argument to Zend_Form::isValid
Example #5 Simple example of testing a CSRF-protected form
public function testCsrfProtectedForm() { $form = new Zend_Form(); $form->addElement(new Zend_Form_Element_Hash('csrf')); $csrf = $form->getElement('csrf'); $csrf->initCsrfToken(); $csrf->initCsrfValidator(); 'csrf' => $csrf->getHash() ))); }
Images can be used as form elements, and you can use these images as graphical elements on 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.
Image elements use the Image Decorator for rendering, in addition to the standard Errors, HtmlTag, and Label decorators. You can optionally specify a tag to the Image decorator that will then wrap the image element.
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":
Note that even when setting a single value, you must pass an array.
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.
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).
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()
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.
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.
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.
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.
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.
Creating Custom Form Markup Using Zend_Form_Decorator