Creating Custom Form Markup Using Zend_Form_Decorator | Zend_Form Programmer's Reference Guide | Standard Form Decorators Shipped With Zend Framework

# 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, 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.

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:

1. $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:

1. // Concrete instance:
2. $element->setCaptcha(new Zend_Captcha_Figlet());
4. // Using shortnames:
5. $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':

1. // Using single captcha key:
2. $element = new Zend_Form_Element_Captcha('foo', array(
3. 'label' => "Please verify you're a human",
4. 'captcha' => array(
5. 'captcha' => 'Figlet',
6. 'wordLen' => 6,
7. 'timeout' => 300,
8. ),
9. ));
11. // Using both captcha and captchaOptions:
12. $element = new Zend_Form_Element_Captcha('foo', array(
13. 'label' => "Please verify you're a human",
14. 'captcha' => 'Figlet',
15. 'captchaOptions' => array(
16. 'captcha' => 'Figlet',
17. 'wordLen' => 6,
18. 'timeout' => 300,
19. ),
20. ));

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

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

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

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:

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

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

1. if (!$form->isValid()) {
2. print "Uh oh... validation error";
3. }
5. if (!$form->foo->receive()) {
6. print "Error receiving the file";
7. }
9. $location = $form->foo->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.

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.

1. $form->getValues();

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

1. $element = new Zend_Form_Element_File('foo');
2. $element->setLabel('Upload an image:')
3. ->setDestination('/var/www/upload')
4. ->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.

1. $values = $form->getValues();
3. if ($form->isValid($form->getPost())) {
4. if (!$form->foo->receive()) {
5. print "Upload error";
6. }
7. }

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

1. $element = new Zend_Form_Element_File('foo');
2. $element->setLabel('Upload an image:')
3. ->setDestination('/var/www/upload')
4. ->setRequired(false);
5. $element->addValidator('Size', false, 102400);
6. $form->addElement($element, 'foo');
8. // The foo file element is optional but when it's given go into here
9. if ($form->foo->isUploaded()) {
10. // foo file given... do something
11. }

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:

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

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.

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

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

# Zend_Form_Element_Hidden

Hidden elements inject data that should be submitted, but that should not manipulated by the user . Zend_Form_Element_Hidden accomplishes this with 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. We recommend using the salt option for the element- two hashes with same names and different salts would not collide:

1. $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 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.

# 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":

1. $element = new Zend_Form_Element_MultiCheckbox('foo', array(
2. 'multiOptions' => array(
3. 'foo' => 'Foo Option',
4. 'bar' => 'Bar Option',
5. 'baz' => 'Baz Option',
6. 'bat' => 'Bat Option',
7. );
8. ));
10. $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.

Creating Custom Form Markup Using Zend_Form_Decorator | Zend_Form Programmer's Reference Guide | Standard Form Decorators Shipped With Zend Framework