Documentation

Dojo Form Elements and Decorators - Zend_Dojo

Dojo Form Elements and Decorators

Building on the dijit view helpers, the Zend_Dojo_Form family of classes provides the ability to utilize Dijits natively within your forms.

There are three options for utilizing the Dojo form elements with your forms:

  • Use Zend_Dojo::enableForm(). This will add plugin paths for decorators and elements to all attached form items, recursively. Additionally, it will dojo-enable the view object. Note, however, that any sub forms you attach after this call will also need to be passed through Zend_Dojo::enableForm().

  • Use the Dojo-specific form and subform implementations, Zend_Dojo_Form and Zend_Dojo_Form_SubForm respectively. These can be used as drop-in replacements for Zend_Form and Zend_Form_SubForm, contain all the appropriate decorator and element paths, set a Dojo-specific default DisplayGroup class, and dojo-enable the view.

  • Last, and most tedious, you can set the appropriate decorator and element paths yourself, set the default DisplayGroup class, and dojo-enable the view. Since Zend_Dojo::enableForm() does this already, there's little reason to go this route.

Example #1 Enabling Dojo in your existing forms

"But wait," you say; "I'm already extending Zend_Form with my own custom form class! How can I Dojo-enable it?'"

First, and easiest, simply change from extending Zend_Form to extending Zend_Dojo_Form, and update any places where you instantiate Zend_Form_SubForm to instantiate Zend_Dojo_Form_SubForm.

A second approach is to call Zend_Dojo::enableForm() within your custom form's init() method; when the form definition is complete, loop through all SubForms to dojo-enable them:

  1. class My_Form_Custom extends Zend_Form
  2. {
  3.     public function init()
  4.     {
  5.         // Dojo-enable the form:
  6.         Zend_Dojo::enableForm($this);
  7.  
  8.         // ... continue form definition from here
  9.  
  10.         // Dojo-enable all sub forms:
  11.         foreach ($this->getSubForms() as $subForm) {
  12.             Zend_Dojo::enableForm($subForm);
  13.         }
  14.     }
  15. }

Usage of the dijit-specific form decorators and elements is just like using any other form decorator or element.

Dijit-Specific Form Decorators

Most form elements can use the DijitElement decorator, which will grab the dijit parameters from the elements, and pass these and other metadata to the view helper specified by the element. For decorating forms, sub forms, and display groups, however, there are a set of decorators corresponding to the various layout dijits.

All dijit decorators look for the dijitParams property of the given element being decorated, and push them as the $params array to the dijit view helper being used; these are then separated from any other properties so that no duplication of information occurs.

DijitElement Decorator

Just like the ViewHelper decorator, DijitElement expects a helper property in the element which it will then use as the view helper when rendering. Dijit parameters will typically be pulled directly from the element, but may also be passed in as options via the dijitParams key (the value of that key should be an associative array of options).

It is important that each element have a unique ID (as fetched from the element's getId() method). If duplicates are detected within the dojo() view helper, the decorator will trigger a notice, but then create a unique ID by appending the return of uniqid() to the identifier.

Standard usage is to simply associate this decorator as the first in your decorator chain, with no additional options.

Example #2 DijitElement Decorator Usage

  1. $element->setDecorators(array(
  2.     'DijitElement',
  3.     'Errors',
  4.     'Label',
  5.     'ContentPane',
  6. ));

DijitForm Decorator

The DijitForm decorator is very similar to the Form decorator; in fact, it can be used basically interchangeably with it, as it utilizes the same view helper name ('form').

Since dijit.form.Form does not require any dijit parameters for configuration, the main difference is that the dijit form view helper require that a DOM ID is passed to ensure that programmatic dijit creation can work. The decorator ensures this, by passing the form name as the identifier.

DijitContainer-based Decorators

The DijitContainer decorator is actually an abstract class from which a variety of other decorators derive. It offers the same functionality of DijitElement, with the addition of title support. Many layout dijits require or can utilize a title; DijitContainer will utilize the element's legend property, if available, and can also utilize either the 'legend' or 'title' decorator option, if passed. The title will be translated if a translation adapter with a corresponding translation is present.

The following is a list of decorators that inherit from DijitContainer:

  • AccordionContainer

  • AccordionPane

  • BorderContainer

  • ContentPane

  • SplitContainer

  • StackContainer

  • TabContainer

Example #3 DijitContainer Decorator Usage

  1. // Use a TabContainer for your form:
  2. $form->setDecorators(array(
  3.     'FormElements',
  4.     array('TabContainer', array(
  5.         'id'          => 'tabContainer',
  6.         'style'       => 'width: 600px; height: 500px;',
  7.         'dijitParams' => array(
  8.             'tabPosition' => 'top'
  9.         ),
  10.     )),
  11.     'DijitForm',
  12. ));
  13.  
  14. // Use a ContentPane in your sub form (which can be used with all but
  15. // AccordionContainer):
  16. $subForm->setDecorators(array(
  17.     'FormElements',
  18.     array('HtmlTag', array('tag' => 'dl')),
  19.     'ContentPane',
  20. ));

Dijit-Specific Form Elements

Each form dijit for which a view helper is provided has a corresponding Zend_Form element. All of them have the following methods available for manipulating dijit parameters:

  • setDijitParam($key, $value): set a single dijit parameter. If the dijit parameter already exists, it will be overwritten.

  • setDijitParams(array $params): set several dijit parameters at once. Any passed parameters matching those already present will overwrite.

  • hasDijitParam($key): If a given dijit parameter is defined and present, return TRUE, otherwise return FALSE.

  • getDijitParam($key): retrieve the given dijit parameter. If not available, a NULL value is returned.

  • getDijitParams(): retrieve all dijit parameters.

  • removeDijitParam($key): remove the given dijit parameter.

  • clearDijitParams(): clear all currently defined dijit parameters.

Dijit parameters are stored in the dijitParams public property. Thus, you can dijit-enable an existing form element simply by setting this property on the element; you simply will not have the above accessors to facilitate manipulating the parameters.

Additionally, dijit-specific elements implement a different list of decorators, corresponding to the following:

  1. $element->addDecorator('DijitElement')
  2.         ->addDecorator('Errors')
  3.         ->addDecorator('HtmlTag', array('tag' => 'dd'))
  4.         ->addDecorator('Label', array('tag' => 'dt'));

In effect, the DijitElement decorator is used in place of the standard ViewHelper decorator.

Finally, the base Dijit element ensures that the Dojo view helper path is set on the view.

A variant on DijitElement, DijitMulti, provides the functionality of the Multi abstract form element, allowing the developer to specify 'multiOptions' -- typically select options or radio options.

The following dijit elements are shipped in the standard Zend Framework distribution.

Button

While not deriving from the standard Button element, it does implement the same functionality, and can be used as a drop-in replacement for it. The following functionality is exposed:

  • getLabel() will utilize the element name as the button label if no name is provided. Additionally, it will translate the name if a translation adapter with a matching translation message is available.

  • isChecked() determines if the value submitted matches the label; if so, it returns TRUE. This is useful for determining which button was used when a form was submitted.

Additionally, only the decorators DijitElement and DtDdWrapper are utilized for Button elements.

Example #4 Example Button dijit element usage

  1. $form->addElement(
  2.     'Button',
  3.     'foo',
  4.     array(
  5.         'label' => 'Button Label',
  6.     )
  7. );

CheckBox

While not deriving from the standard Checkbox element, it does implement the same functionality. This means that the following methods are exposed:

  • setCheckedValue($value): set the value to use when the element is checked.

  • getCheckedValue(): get the value of the item to use when checked.

  • setUncheckedValue($value): set the value of the item to use when it is unchecked.

  • getUncheckedValue(): get the value of the item to use when it is unchecked.

  • setChecked($flag): mark the element as checked or unchecked.

  • isChecked(): determine if the element is currently checked.

Example #5 Example CheckBox dijit element usage

  1. $form->addElement(
  2.     'CheckBox',
  3.     'foo',
  4.     array(
  5.         'label'          => 'A check box',
  6.         'checkedValue'   => 'foo',
  7.         'uncheckedValue' => 'bar',
  8.         'checked'        => true,
  9.     )
  10. );

ComboBox and FilteringSelect

As noted in the ComboBox dijit view helper documentation, ComboBoxes are a hybrid between select and text input, allowing for autocompletion and the ability to specify an alternate to the options provided. FilteringSelects are the same, but do not allow arbitrary input.

Note: ComboBoxes return the label values
ComboBoxes return the label values, and not the option values, which can lead to a disconnect in expectations. For this reason, ComboBoxes do not auto-register an InArray validator (though FilteringSelects do).

The ComboBox and FilteringSelect form elements provide accessors and mutators for examining and setting the select options as well as specifying a dojo.data datastore (if used). They extend from DijitMulti, which allows you to specify select options via the setMultiOptions() and setMultiOption() methods. In addition, the following methods are available:

  • getStoreInfo(): get all datastore information currently set. Returns an empty array if no data is currently set.

  • setStoreId($identifier): set the store identifier variable (usually referred to by the attribute 'jsId' in Dojo). This should be a valid javascript variable name.

  • getStoreId(): retrieve the store identifier variable name.

  • setStoreType($dojoType): set the datastore class to use; e.g., "dojo.data.ItemFileReadStore".

  • getStoreType(): get the dojo datastore class to use.

  • setStoreParams(array $params): set any parameters used to configure the datastore object. As an example, dojo.data.ItemFileReadStore datastore would expect a 'url' parameter pointing to a location that would return the dojo.data object.

  • getStoreParams(): get any datastore parameters currently set; if none, an empty array is returned.

  • setAutocomplete($flag): indicate whether or not the selected item will be used when the user leaves the element.

  • getAutocomplete(): get the value of the autocomplete flag.

By default, if no dojo.data store is registered with the element, 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.

Example #6 ComboBox dijit element usage as select input

  1. $form->addElement(
  2.     'ComboBox',
  3.     'foo',
  4.     array(
  5.         'label'        => 'ComboBox (select)',
  6.         'value'        => 'blue',
  7.         'autocomplete' => false,
  8.         'multiOptions' => array(
  9.             'red'    => 'Rouge',
  10.             'blue'   => 'Bleu',
  11.             'white'  => 'Blanc',
  12.             'orange' => 'Orange',
  13.             'black'  => 'Noir',
  14.             'green'  => 'Vert',
  15.         ),
  16.     )
  17. );

Example #7 ComboBox dijit element usage with datastore

  1. $form->addElement(
  2.     'ComboBox',
  3.     'foo',
  4.     array(
  5.         'label'       => 'ComboBox (datastore)',
  6.         'storeId'     => 'stateStore',
  7.         'storeType'   => 'dojo.data.ItemFileReadStore',
  8.         'storeParams' => array(
  9.             'url' => '/js/states.txt',
  10.         ),
  11.         'dijitParams' => array(
  12.             'searchAttr' => 'name',
  13.         ),
  14.     )
  15. );

The above examples could also utilize FilteringSelect instead of ComboBox.

CurrencyTextBox

The CurrencyTextBox is primarily for supporting currency input. The currency may be localized, and can support both fractional and non-fractional values.

Internally, CurrencyTextBox derives from NumberTextBox, ValidationTextBox, and TextBox; all methods available to those classes are available. In addition, the following constraint methods can be used:

  • setCurrency($currency): set the currency type to use; should follow the » ISO-4217 specification.

  • getCurrency(): retrieve the current currency type.

  • setSymbol($symbol): set the 3-letter » ISO-4217 currency symbol to use.

  • getSymbol(): get the current currency symbol.

  • setFractional($flag): set whether or not the currency should allow for fractional values.

  • getFractional(): retrieve the status of the fractional flag.

Example #8 Example CurrencyTextBox dijit element usage

  1. $form->addElement(
  2.     'CurrencyTextBox',
  3.     'foo',
  4.     array(
  5.         'label'          => 'Currency:',
  6.         'required'       => true,
  7.         'currency'       => 'USD',
  8.         'invalidMessage' => 'Invalid amount. ' .
  9.                             'Include dollar sign, commas, and cents.',
  10.         'fractional'     => false,
  11.     )
  12. );

DateTextBox

DateTextBox provides a calendar drop-down for selecting a date, as well as client-side date validation and formatting.

Internally, DateTextBox derives from ValidationTextBox and TextBox; all methods available to those classes are available. In addition, the following methods can be used to set individual constraints:

  • setAmPm($flag) and getAmPm(): Whether or not to use AM or PM strings in times.

  • setStrict($flag) and getStrict(): whether or not to use strict regular expression matching when validating input. If FALSE, which is the default, it will be lenient about whitespace and some abbreviations.

  • setLocale($locale) and getLocale(): Set and retrieve the locale to use with this specific element.

  • setDatePattern($pattern) and getDatePattern(): provide and retrieve the » unicode date format pattern for formatting the date.

  • setFormatLength($formatLength) and getFormatLength(): provide and retrieve the format length type to use; should be one of "long", "short", "medium" or "full".

  • setSelector($selector) and getSelector(): provide and retrieve the style of selector; should be either "date" or "time".

Example #9 Example DateTextBox dijit element usage

  1. $form->addElement(
  2.     'DateTextBox',
  3.     'foo',
  4.     array(
  5.         'label'          => 'Date:',
  6.         'required'       => true,
  7.         'invalidMessage' => 'Invalid date specified.',
  8.         'formatLength'   => 'long',
  9.     )
  10. );

Editor

Editor provides a WYSIWYG editor that can be used to both create and edit rich HTML content. dijit.Editor is pluggable and may be extended with custom plugins if desired; see » the dijit.Editor documentation for more details.

The Editor form element provides a number of accessors and mutators for manipulating various dijit parameters, as follows:

  • captureEvents are events that connect to the editing area itself. The following accessors and mutators are available for manipulating capture events:

    • addCaptureEvent($event)

    • addCaptureEvents(array $events)

    • setCaptureEvents(array $events)

    • getCaptureEvents()

    • hasCaptureEvent($event)

    • removeCaptureEvent($event)

    • clearCaptureEvents()

  • events are standard DOM events, such as onClick, onKeyUp, etc. The following accessors and mutators are available for manipulating events:

    • addEvent($event)

    • addEvents(array $events)

    • setEvents(array $events)

    • getEvents()

    • hasEvent($event)

    • removeEvent($event)

    • clearEvents()

  • plugins add functionality to the Editor -- additional tools for the toolbar, additional styles to allow, etc. The following accessors and mutators are available for manipulating plugins:

    • addPlugin($plugin)

    • addPlugins(array $plugins)

    • setPlugins(array $plugins)

    • getPlugins()

    • hasPlugin($plugin)

    • removePlugin($plugin)

    • clearPlugins()

  • editActionInterval is used to group events for undo operations. By default, this value is 3 seconds. The method setEditActionInterval($interval) may be used to set the value, while getEditActionInterval() will retrieve it.

  • focusOnLoad is used to determine whether this particular editor will receive focus when the page has loaded. By default, this is FALSE. The method setFocusOnLoad($flag) may be used to set the value, while getFocusOnLoad() will retrieve it.

  • height specifies the height of the editor; by default, this is 300px. The method setHeight($height) may be used to set the value, while getHeight() will retrieve it.

  • inheritWidth is used to determine whether the editor will use the parent container's width or simply default to 100% width. By default, this is FALSE (i.e., it will fill the width of the window). The method setInheritWidth($flag) may be used to set the value, while getInheritWidth() will retrieve it.

  • minHeight indicates the minimum height of the editor; by default, this is 1em. The method setMinHeight($height) may be used to set the value, while getMinHeight() will retrieve it.

  • styleSheets indicate what additional CSS stylesheets should be used to affect the display of the Editor. By default, none are registered, and it inherits the page styles. The following accessors and mutators are available for manipulating editor stylesheets:

    • addStyleSheet($styleSheet)

    • addStyleSheets(array $styleSheets)

    • setStyleSheets(array $styleSheets)

    • getStyleSheets()

    • hasStyleSheet($styleSheet)

    • removeStyleSheet($styleSheet)

    • clearStyleSheets()

Example #10 Example Editor dijit element usage

  1. $form->addElement('editor', 'content', array(
  2.     'plugins'            => array('undo', '|', 'bold', 'italic'),
  3.     'editActionInterval' => 2,
  4.     'focusOnLoad'        => true,
  5.     'height'             => '250px',
  6.     'inheritWidth'       => true,
  7.     'styleSheets'        => array('/js/custom/editor.css'),
  8. ));

Note: Editor Dijit uses div by default
The Editor dijit uses an HTML DIV by default. The dijit._editor.RichText documentation indicates that having it built on an HTML TEXTAREA can potentially have security implications.
That said, there may be times when you want an Editor widget that can gracefully degrade to a TEXTAREA. In such situations, you can do so by setting the degrade property to TRUE:

  1. // At instantiation:
  2. $editor = new Zend_Dojo_Form_Element_Editor('foo', array(
  3.     'degrade' => true,
  4. ));
  5.  
  6. // Construction via the form:
  7. $form->addElement('editor', 'content', array(
  8.     'degrade' => true,
  9. ));
  10.  
  11. // Or after instantiation:
  12. $editor->degrade = true;

HorizontalSlider

HorizontalSlider provides a slider UI widget for selecting a numeric value in a range. Internally, it sets the value of a hidden element which is submitted by the form.

HorizontalSlider derives from the abstract Slider dijit element. Additionally, it has a variety of methods for setting and configuring slider rules and rule labels.

  • setTopDecorationDijit($dijit) and setBottomDecorationDijit($dijit): set the name of the dijit to use for either the top or bottom of the slider. This should not include the "dijit.form." prefix, but rather only the final name -- one of "HorizontalRule" or "HorizontalRuleLabels".

  • setTopDecorationContainer($container) and setBottomDecorationContainer($container): specify the name to use for the container element of the rules; e.g. 'topRule', 'topContainer', etc.

  • setTopDecorationLabels(array $labels) and setBottomDecorationLabels(array $labels): set the labels to use for one of the RuleLabels dijit types. These should be an indexed array; specify a single empty space to skip a given label position (such as the beginning or end).

  • setTopDecorationParams(array $params) and setBottomDecorationParams(array $params): dijit parameters to use when configuring the given Rule or RuleLabels dijit.

  • setTopDecorationAttribs(array $attribs) and setBottomDecorationAttribs(array $attribs): HTML attributes to specify for the given Rule or RuleLabels HTML element container.

  • getTopDecoration() and getBottomDecoration(): retrieve all metadata for a given Rule or RuleLabels definition, as provided by the above mutators.

Example #11 Example HorizontalSlider dijit element usage

The following will create a horizontal slider selection with integer values ranging from -10 to 10. The top will have labels at the 20%, 40%, 60%, and 80% marks. The bottom will have rules at 0, 50%, and 100%. Each time the value is changed, the hidden element storing the value will be updated.

  1. $form->addElement(
  2.     'HorizontalSlider',
  3.     'horizontal',
  4.     array(
  5.         'label'                     => 'HorizontalSlider',
  6.         'value'                     => 5,
  7.         'minimum'                   => -10,
  8.         'maximum'                   => 10,
  9.         'discreteValues'            => 11,
  10.         'intermediateChanges'       => true,
  11.         'showButtons'               => true,
  12.         'topDecorationDijit'        => 'HorizontalRuleLabels',
  13.         'topDecorationContainer'    => 'topContainer',
  14.         'topDecorationLabels'       => array(
  15.                 ' ',
  16.                 '20%',
  17.                 '40%',
  18.                 '60%',
  19.                 '80%',
  20.                 ' ',
  21.         ),
  22.         'topDecorationParams'      => array(
  23.             'container' => array(
  24.                 'style' => 'height:1.2em; font-size=75%;color:gray;',
  25.             ),
  26.             'list' => array(
  27.                 'style' => 'height:1em; font-size=75%;color:gray;',
  28.             ),
  29.         ),
  30.         'bottomDecorationDijit'     => 'HorizontalRule',
  31.         'bottomDecorationContainer' => 'bottomContainer',
  32.         'bottomDecorationLabels'    => array(
  33.                 '0%',
  34.                 '50%',
  35.                 '100%',
  36.         ),
  37.         'bottomDecorationParams'   => array(
  38.             'list' => array(
  39.                 'style' => 'height:1em; font-size=75%;color:gray;',
  40.             ),
  41.         ),
  42.     )
  43. );

NumberSpinner

A number spinner is a text element for entering numeric values; it also includes elements for incrementing and decrementing the value by a set amount.

The following methods are available:

  • setDefaultTimeout($timeout) and getDefaultTimeout(): set and retrieve the default timeout, in milliseconds, between when the button is held pressed and the value is changed.

  • setTimeoutChangeRate($rate) and getTimeoutChangeRate(): set and retrieve the rate, in milliseconds, at which changes will be made when a button is held pressed.

  • setLargeDelta($delta) and getLargeDelta(): set and retrieve the amount by which the numeric value should change when a button is held pressed.

  • setSmallDelta($delta) and getSmallDelta(): set and retrieve the delta by which the number should change when a button is pressed once.

  • setIntermediateChanges($flag) and getIntermediateChanges(): set and retrieve the flag indicating whether or not each value change should be shown when a button is held pressed.

  • setRangeMessage($message) and getRangeMessage(): set and retrieve the message indicating the range of values available.

  • setMin($value) and getMin(): set and retrieve the minimum value possible.

  • setMax($value) and getMax(): set and retrieve the maximum value possible.

Example #12 Example NumberSpinner dijit element usage

  1. $form->addElement(
  2.     'NumberSpinner',
  3.     'foo',
  4.     array(
  5.         'value'             => '7',
  6.         'label'             => 'NumberSpinner',
  7.         'smallDelta'        => 5,
  8.         'largeDelta'        => 25,
  9.         'defaultTimeout'    => 500,
  10.         'timeoutChangeRate' => 100,
  11.         'min'               => 9,
  12.         'max'               => 1550,
  13.         'places'            => 0,
  14.         'maxlength'         => 20,
  15.     )
  16. );

NumberTextBox

A number text box is a text element for entering numeric values; unlike NumberSpinner, numbers are entered manually. Validations and constraints can be provided to ensure the number stays in a particular range or format.

Internally, NumberTextBox derives from ValidationTextBox and TextBox; all methods available to those classes are available. In addition, the following methods can be used to set individual constraints:

  • setLocale($locale) and getLocale(): specify and retrieve a specific or alternate locale to use with this dijit.

  • setPattern($pattern) and getPattern(): set and retrieve a » number pattern format to use to format the number.

  • setType($type) and getType(): set and retrieve the numeric format type to use (should be one of 'decimal', 'percent', or 'currency').

  • setPlaces($places) and getPlaces(): set and retrieve the number of decimal places to support.

  • setStrict($flag) and getStrict(): set and retrieve the value of the strict flag, which indicates how much leniency is allowed in relation to whitespace and non-numeric characters.

Example #13 Example NumberTextBox dijit element usage

  1. $form->addElement(
  2.     'NumberTextBox',
  3.     'elevation',
  4.     array(
  5.         'label'          => 'NumberTextBox',
  6.         'required'       => true,
  7.         'invalidMessage' => 'Invalid elevation.',
  8.         'places'         => 0,
  9.         'constraints'    => array(
  10.             'min'    => -20000,
  11.             'max'    => 20000,
  12.         ),
  13.     )
  14. );

PasswordTextBox

PasswordTextBox is simply a ValidationTextBox that is tied to a password input; its sole purpose is to allow for a dijit-themed text entry for passwords that also provides client-side validation.

Internally, PasswordTextBox derives from ValidationTextBox and TextBox; all methods available to those classes are available.

Example #14 Example PasswordTextBox dijit element usage

  1. $form->addElement(
  2.     'PasswordTextBox',
  3.     'password',
  4.     array(
  5.         'label'          => 'Password',
  6.         'required'       => true,
  7.         'trim'           => true,
  8.         'lowercase'      => true,
  9.         'regExp'         => '^[a-z0-9]{6,}$',
  10.         'invalidMessage' => 'Invalid password; ' .
  11.                             'must be at least 6 alphanumeric characters',
  12.     )
  13. );

RadioButton

RadioButton wraps standard radio input elements to provide a consistent look and feel with other dojo dijits.

RadioButton extends from DijitMulti, which allows you to specify select options via the setMultiOptions() and setMultiOption() methods.

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.

Example #15 Example RadioButton dijit element usage

  1. $form->addElement(
  2.     'RadioButton',
  3.     'foo',
  4.     array(
  5.         'label' => 'RadioButton',
  6.         'multiOptions'  => array(
  7.             'foo' => 'Foo',
  8.             'bar' => 'Bar',
  9.             'baz' => 'Baz',
  10.         ),
  11.         'value' => 'bar',
  12.     )
  13. );

SimpleTextarea

SimpleTextarea acts primarily like a standard HTML textarea. However, it does not support either the rows or cols settings. Instead, the textarea width should be specified using standard CSS measurements. Unlike Textarea, it will not grow automatically

Example #16 Example SimpleTextarea dijit element usage

  1. $form->addElement(
  2.     'SimpleTextarea',
  3.     'simpletextarea',
  4.     array(
  5.         'label'    => 'SimpleTextarea',
  6.         'required' => true,
  7.         'style'    => 'width: 80em; height: 25em;',
  8.     )
  9. );

Slider abstract element

Slider is an abstract element from which HorizontalSlider and VerticalSlider both derive. It exposes a number of common methods for configuring your sliders, including:

  • setClickSelect($flag) and getClickSelect(): set and retrieve the flag indicating whether or not clicking the slider changes the value.

  • setIntermediateChanges($flag) and getIntermediateChanges(): set and retrieve the flag indicating whether or not the dijit will send a notification on each slider change event.

  • setShowButtons($flag) and getShowButtons(): set and retrieve the flag indicating whether or not buttons on either end will be displayed; if so, the user can click on these to change the value of the slider.

  • setDiscreteValues($value) and getDiscreteValues(): set and retrieve the number of discrete values represented by the slider.

  • setMaximum($value) and getMaximum(): set the maximum value of the slider.

  • setMinimum($value) and getMinimum(): set the minimum value of the slider.

  • setPageIncrement($value) and getPageIncrement(): set the amount by which the slider will change on keyboard events.

Example usage is provided with each concrete extending class.

SubmitButton

While there is no Dijit named SubmitButton, we include one here to provide a button dijit capable of submitting a form without requiring any additional javascript bindings. It works exactly like the Button dijit.

Example #17 Example SubmitButton dijit element usage

  1. $form->addElement(
  2.     'SubmitButton',
  3.     'foo',
  4.     array(
  5.         'required'   => false,
  6.         'ignore'     => true,
  7.         'label'      => 'Submit Button!',
  8.     )
  9. );

TextBox

TextBox is included primarily to provide a text input with consistent look-and-feel to the other dijits. However, it also includes some minor filtering and validation capabilities, represented in the following methods:

  • setLowercase($flag) and getLowercase(): set and retrieve the flag indicating whether or not input should be cast to lowercase.

  • setPropercase($flag) and getPropercase(): set and retrieve the flag indicating whether or not the input should be cast to Proper Case.

  • setUppercase($flag) and getUppercase(): set and retrieve the flag indicating whether or not the input should be cast to UPPERCASE.

  • setTrim($flag) and getTrim(): set and retrieve the flag indicating whether or not leading or trailing whitespace should be stripped.

  • setMaxLength($length) and getMaxLength(): set and retrieve the maximum length of input.

Example #18 Example TextBox dijit element usage

  1. $form->addElement(
  2.     'TextBox',
  3.     'foo',
  4.     array(
  5.         'value'      => 'some text',
  6.         'label'      => 'TextBox',
  7.         'trim'       => true,
  8.         'propercase' => true,
  9.     )
  10. );

Textarea

Textarea acts primarily like a standard HTML textarea. However, it does not support either the rows or cols settings. Instead, the textarea width should be specified using standard CSS measurements; rows should be omitted entirely. The textarea will then grow vertically as text is added to it.

Example #19 Example Textarea dijit element usage

  1. $form->addElement(
  2.     'Textarea',
  3.     'textarea',
  4.     array(
  5.         'label'    => 'Textarea',
  6.         'required' => true,
  7.         'style'    => 'width: 200px;',
  8.     )
  9. );

TimeTextBox

TimeTextBox is a text input that provides a drop-down for selecting a time. The drop-down may be configured to show a certain window of time, with specified increments.

Internally, TimeTextBox derives from DateTextBox, ValidationTextBox and TextBox; all methods available to those classes are available. In addition, the following methods can be used to set individual constraints:

  • setTimePattern($pattern) and getTimePattern(): set and retrieve the » unicode time format pattern for formatting the time.

  • setClickableIncrement($format) and getClickableIncrement(): set the » ISO_8601 string representing the amount by which every clickable element in the time picker increases.

  • setVisibleIncrement($format) and getVisibleIncrement(): set the increment visible in the time chooser; must follow ISO_8601 formats.

  • setVisibleRange($format) and getVisibleRange(): set and retrieve the range of time visible in the time chooser at any given moment; must follow ISO_8601 formats.

Example #20 Example TimeTextBox dijit element usage

The following will create a TimeTextBox that displays 2 hours at a time, with increments of 10 minutes.

  1. $form->addElement(
  2.     'TimeTextBox',
  3.     'foo',
  4.     array(
  5.         'label'              => 'TimeTextBox',
  6.         'required'           => true,
  7.         'visibleRange'       => 'T04:00:00',
  8.         'visibleIncrement'   => 'T00:10:00',
  9.         'clickableIncrement' => 'T00:10:00',
  10.     )
  11. );

ValidationTextBox

ValidationTextBox provides the ability to add validations and constraints to a text input. Internally, it derives from TextBox, and adds the following accessors and mutators for manipulating dijit parameters:

  • setInvalidMessage($message) and getInvalidMessage(): set and retrieve the tooltip message to display when the value does not validate.

  • setPromptMessage($message) and getPromptMessage(): set and retrieve the tooltip message to display for element usage.

  • setRegExp($regexp) and getRegExp(): set and retrieve the regular expression to use for validating the element. The regular expression does not need boundaries (unlike PHP's preg* family of functions).

  • setConstraint($key, $value) and getConstraint($key): set and retrieve additional constraints to use when validating the element; used primarily with subclasses. Constraints are stored in the 'constraints' key of the dijit parameters.

  • setConstraints(array $constraints) and getConstraints(): set and retrieve individual constraints to use when validating the element; used primarily with subclasses.

  • hasConstraint($key): test whether a given constraint exists.

  • removeConstraint($key) and clearConstraints(): remove an individual or all constraints for the element.

Example #21 Example ValidationTextBox dijit element usage

The following will create a ValidationTextBox that requires a single string consisting solely of word characters (i.e., no spaces, most punctuation is invalid).

  1. $form->addElement(
  2.     'ValidationTextBox',
  3.     'foo',
  4.     array(
  5.         'label'          => 'ValidationTextBox',
  6.         'required'       => true,
  7.         'regExp'         => '[\w]+',
  8.         'invalidMessage' => 'Invalid non-space text.',
  9.     )
  10. );

VerticalSlider

VerticalSlider is the sibling of HorizontalSlider, and operates in every way like that element. The only real difference is that the 'top*' and 'bottom*' methods are replaced by 'left*' and 'right*', and instead of using HorizontalRule and HorizontalRuleLabels, VerticalRule and VerticalRuleLabels should be used.

Example #22 Example VerticalSlider dijit element usage

The following will create a vertical slider selection with integer values ranging from -10 to 10. The left will have labels at the 20%, 40%, 60%, and 80% marks. The right will have rules at 0, 50%, and 100%. Each time the value is changed, the hidden element storing the value will be updated.

  1. $form->addElement(
  2.     'VerticalSlider',
  3.     'foo',
  4.     array(
  5.         'label'                    => 'VerticalSlider',
  6.         'value'                    => 5,
  7.         'style'                    => 'height: 200px; width: 3em;',
  8.         'minimum'                  => -10,
  9.         'maximum'                  => 10,
  10.         'discreteValues'           => 11,
  11.         'intermediateChanges'      => true,
  12.         'showButtons'              => true,
  13.         'leftDecorationDijit'      => 'VerticalRuleLabels',
  14.         'leftDecorationContainer'  => 'leftContainer',
  15.         'leftDecorationLabels'     => array(
  16.                 ' ',
  17.                 '20%',
  18.                 '40%',
  19.                 '60%',
  20.                 '80%',
  21.                 ' ',
  22.         ),
  23.         'rightDecorationDijit' => 'VerticalRule',
  24.         'rightDecorationContainer' => 'rightContainer',
  25.         'rightDecorationLabels' => array(
  26.                 '0%',
  27.                 '50%',
  28.                 '100%',
  29.         ),
  30.     )
  31. );

Dojo Form Examples

Example #23 Using Zend_Dojo_Form

The easiest way to utilize Dojo with Zend_Form is to utilize Zend_Dojo_Form, either through direct usage or by extending it. This example shows extending Zend_Dojo_Form, and shows usage of all dijit elements. It creates four sub forms, and decorates the form to utilize a TabContainer, showing each sub form in its own tab.

  1. class My_Form_Test extends Zend_Dojo_Form
  2. {
  3.     /**
  4.      * Options to use with select elements
  5.      */
  6.     protected $_selectOptions = array(
  7.         'red'    => 'Rouge',
  8.         'blue'   => 'Bleu',
  9.         'white'  => 'Blanc',
  10.         'orange' => 'Orange',
  11.         'black'  => 'Noir',
  12.         'green'  => 'Vert',
  13.     );
  14.  
  15.     /**
  16.      * Form initialization
  17.      *
  18.      * @return void
  19.      */
  20.     public function init()
  21.     {
  22.         $this->setMethod('post');
  23.         $this->setAttribs(array(
  24.             'name'  => 'masterForm',
  25.         ));
  26.         $this->setDecorators(array(
  27.             'FormElements',
  28.             array('TabContainer', array(
  29.                 'id' => 'tabContainer',
  30.                 'style' => 'width: 600px; height: 500px;',
  31.                 'dijitParams' => array(
  32.                     'tabPosition' => 'top'
  33.                 ),
  34.             )),
  35.             'DijitForm',
  36.         ));
  37.         $textForm = new Zend_Dojo_Form_SubForm();
  38.         $textForm->setAttribs(array(
  39.             'name'   => 'textboxtab',
  40.             'legend' => 'Text Elements',
  41.             'dijitParams' => array(
  42.                 'title' => 'Text Elements',
  43.             ),
  44.         ));
  45.         $textForm->addElement(
  46.                 'TextBox',
  47.                 'textbox',
  48.                 array(
  49.                     'value'      => 'some text',
  50.                     'label'      => 'TextBox',
  51.                     'trim'       => true,
  52.                     'propercase' => true,
  53.                 )
  54.             )
  55.             ->addElement(
  56.                 'DateTextBox',
  57.                 'datebox',
  58.                 array(
  59.                     'value' => '2008-07-05',
  60.                     'label' => 'DateTextBox',
  61.                     'required'  => true,
  62.                 )
  63.             )
  64.             ->addElement(
  65.                 'TimeTextBox',
  66.                 'timebox',
  67.                 array(
  68.                     'label' => 'TimeTextBox',
  69.                     'required'  => true,
  70.                 )
  71.             )
  72.             ->addElement(
  73.                 'CurrencyTextBox',
  74.                 'currencybox',
  75.                 array(
  76.                     'label' => 'CurrencyTextBox',
  77.                     'required'  => true,
  78.                     // 'currency' => 'USD',
  79.                     'invalidMessage' => 'Invalid amount. ' .
  80.                                         'Include dollar sign, commas, ' .
  81.                                         'and cents.',
  82.                     // 'fractional' => true,
  83.                     // 'symbol' => 'USD',
  84.                     // 'type' => 'currency',
  85.                 )
  86.             )
  87.             ->addElement(
  88.                 'NumberTextBox',
  89.                 'numberbox',
  90.                 array(
  91.                     'label' => 'NumberTextBox',
  92.                     'required'  => true,
  93.                     'invalidMessage' => 'Invalid elevation.',
  94.                     'constraints' => array(
  95.                         'min' => -20000,
  96.                         'max' => 20000,
  97.                         'places' => 0,
  98.                     )
  99.                 )
  100.             )
  101.             ->addElement(
  102.                 'ValidationTextBox',
  103.                 'validationbox',
  104.                 array(
  105.                     'label' => 'ValidationTextBox',
  106.                     'required'  => true,
  107.                     'regExp' => '[\w]+',
  108.                     'invalidMessage' => 'Invalid non-space text.',
  109.                 )
  110.             )
  111.             ->addElement(
  112.                 'Textarea',
  113.                 'textarea',
  114.                 array(
  115.                     'label'    => 'Textarea',
  116.                     'required' => true,
  117.                     'style'    => 'width: 200px;',
  118.                 )
  119.             );
  120.         $editorForm = new Zend_Dojo_Form_SubForm();
  121.         $editorForm->setAttribs(array(
  122.             'name'   => 'editortab',
  123.             'legend' => 'Editor',
  124.             'dijitParams' => array(
  125.                 'title' => 'Editor'
  126.             ),
  127.         ))
  128.         $editorForm->addElement(
  129.             'Editor',
  130.             'wysiwyg',
  131.             array(
  132.                 'label'        => 'Editor',
  133.                 'inheritWidth' => 'true',
  134.             )
  135.         );
  136.  
  137.         $toggleForm = new Zend_Dojo_Form_SubForm();
  138.         $toggleForm->setAttribs(array(
  139.             'name'   => 'toggletab',
  140.             'legend' => 'Toggle Elements',
  141.         ));
  142.         $toggleForm->addElement(
  143.                 'NumberSpinner',
  144.                 'ns',
  145.                 array(
  146.                     'value'             => '7',
  147.                     'label'             => 'NumberSpinner',
  148.                     'smallDelta'        => 5,
  149.                     'largeDelta'        => 25,
  150.                     'defaultTimeout'    => 1000,
  151.                     'timeoutChangeRate' => 100,
  152.                     'min'               => 9,
  153.                     'max'               => 1550,
  154.                     'places'            => 0,
  155.                     'maxlength'         => 20,
  156.                 )
  157.             )
  158.             ->addElement(
  159.                 'Button',
  160.                 'dijitButton',
  161.                 array(
  162.                     'label' => 'Button',
  163.                 )
  164.             )
  165.             ->addElement(
  166.                 'CheckBox',
  167.                 'checkbox',
  168.                 array(
  169.                     'label' => 'CheckBox',
  170.                     'checkedValue'  => 'foo',
  171.                     'uncheckedValue'  => 'bar',
  172.                     'checked' => true,
  173.                 )
  174.             )
  175.             ->addElement(
  176.                 'RadioButton',
  177.                 'radiobutton',
  178.                 array(
  179.                     'label' => 'RadioButton',
  180.                     'multiOptions'  => array(
  181.                         'foo' => 'Foo',
  182.                         'bar' => 'Bar',
  183.                         'baz' => 'Baz',
  184.                     ),
  185.                     'value' => 'bar',
  186.                 )
  187.             );
  188.         $selectForm = new Zend_Dojo_Form_SubForm();
  189.         $selectForm->setAttribs(array(
  190.             'name'   => 'selecttab',
  191.             'legend' => 'Select Elements',
  192.         ));
  193.         $selectForm->addElement(
  194.                 'ComboBox',
  195.                 'comboboxselect',
  196.                 array(
  197.                     'label' => 'ComboBox (select)',
  198.                     'value' => 'blue',
  199.                     'autocomplete' => false,
  200.                     'multiOptions' => $this->_selectOptions,
  201.                 )
  202.             )
  203.             ->addElement(
  204.                 'ComboBox',
  205.                 'comboboxremote',
  206.                 array(
  207.                     'label' => 'ComboBox (remoter)',
  208.                     'storeId' => 'stateStore',
  209.                     'storeType' => 'dojo.data.ItemFileReadStore',
  210.                     'storeParams' => array(
  211.                         'url' => '/js/states.txt',
  212.                     ),
  213.                     'dijitParams' => array(
  214.                         'searchAttr' => 'name',
  215.                     ),
  216.                 )
  217.             )
  218.             ->addElement(
  219.                 'FilteringSelect',
  220.                 'filterselect',
  221.                 array(
  222.                     'label' => 'FilteringSelect (select)',
  223.                     'value' => 'blue',
  224.                     'autocomplete' => false,
  225.                     'multiOptions' => $this->_selectOptions,
  226.                 )
  227.             )
  228.             ->addElement(
  229.                 'FilteringSelect',
  230.                 'filterselectremote',
  231.                 array(
  232.                     'label' => 'FilteringSelect (remoter)',
  233.                     'storeId' => 'stateStore',
  234.                     'storeType' => 'dojo.data.ItemFileReadStore',
  235.                     'storeParams' => array(
  236.                         'url' => '/js/states.txt',
  237.                     ),
  238.                     'dijitParams' => array(
  239.                         'searchAttr' => 'name',
  240.                     ),
  241.                 )
  242.             );
  243.         $sliderForm = new Zend_Dojo_Form_SubForm();
  244.         $sliderForm->setAttribs(array(
  245.             'name'   => 'slidertab',
  246.             'legend' => 'Slider Elements',
  247.         ));
  248.         $sliderForm->addElement(
  249.                 'HorizontalSlider',
  250.                 'horizontal',
  251.                 array(
  252.                     'label' => 'HorizontalSlider',
  253.                     'value' => 5,
  254.                     'minimum' => -10,
  255.                     'maximum' => 10,
  256.                     'discreteValues' => 11,
  257.                     'intermediateChanges' => true,
  258.                     'showButtons' => true,
  259.                     'topDecorationDijit' => 'HorizontalRuleLabels',
  260.                     'topDecorationContainer' => 'topContainer',
  261.                     'topDecorationLabels' => array(
  262.                             ' ',
  263.                             '20%',
  264.                             '40%',
  265.                             '60%',
  266.                             '80%',
  267.                             ' ',
  268.                     ),
  269.                     'topDecorationParams' => array(
  270.                         'container' => array(
  271.                             'style' => 'height:1.2em; ' .
  272.                                        'font-size=75%;color:gray;',
  273.                         ),
  274.                         'list' => array(
  275.                             'style' => 'height:1em; ' .
  276.                                        'font-size=75%;color:gray;',
  277.                         ),
  278.                     ),
  279.                     'bottomDecorationDijit' => 'HorizontalRule',
  280.                     'bottomDecorationContainer' => 'bottomContainer',
  281.                     'bottomDecorationLabels' => array(
  282.                             '0%',
  283.                             '50%',
  284.                             '100%',
  285.                     ),
  286.                     'bottomDecorationParams' => array(
  287.                         'list' => array(
  288.                             'style' => 'height:1em; ' .
  289.                                        'font-size=75%;color:gray;',
  290.                         ),
  291.                     ),
  292.                 )
  293.             )
  294.             ->addElement(
  295.                 'VerticalSlider',
  296.                 'vertical',
  297.                 array(
  298.                     'label' => 'VerticalSlider',
  299.                     'value' => 5,
  300.                     'style' => 'height: 200px; width: 3em;',
  301.                     'minimum' => -10,
  302.                     'maximum' => 10,
  303.                     'discreteValues' => 11,
  304.                     'intermediateChanges' => true,
  305.                     'showButtons' => true,
  306.                     'leftDecorationDijit' => 'VerticalRuleLabels',
  307.                     'leftDecorationContainer' => 'leftContainer',
  308.                     'leftDecorationLabels' => array(
  309.                             ' ',
  310.                             '20%',
  311.                             '40%',
  312.                             '60%',
  313.                             '80%',
  314.                             ' ',
  315.                     ),
  316.                     'rightDecorationDijit' => 'VerticalRule',
  317.                     'rightDecorationContainer' => 'rightContainer',
  318.                     'rightDecorationLabels' => array(
  319.                             '0%',
  320.                             '50%',
  321.                             '100%',
  322.                     ),
  323.                 )
  324.             );
  325.  
  326.         $this->addSubForm($textForm, 'textboxtab')
  327.              ->addSubForm($editorForm, 'editortab')
  328.              ->addSubForm($toggleForm, 'toggletab')
  329.              ->addSubForm($selectForm, 'selecttab')
  330.              ->addSubForm($sliderForm, 'slidertab');
  331.     }
  332. }

Example #24 Modifying an existing form to utilize Dojo

Existing forms can be modified to utilize Dojo as well, by use of the Zend_Dojo::enableForm() static method.

This first example shows decorating an existing form instance:

  1. $form = new My_Custom_Form();
  2. Zend_Dojo::enableForm($form);
  3. $form->addElement(
  4. 'ComboBox',
  5. 'query',
  6.     'label'        => 'Color:',
  7.     'value'        => 'blue',
  8.     'autocomplete' => false,
  9.     'multiOptions' => array(
  10.         'red'    => 'Rouge',
  11.         'blue'   => 'Bleu',
  12.         'white'  => 'Blanc',
  13.         'orange' => 'Orange',
  14.         'black'  => 'Noir',
  15.         'green'  => 'Vert',
  16.     ),
  17. )
  18. );

Alternately, you can make a slight tweak to your form initialization:

  1. class My_Custom_Form extends Zend_Form
  2. {
  3.     public function init()
  4.     {
  5.         Zend_Dojo::enableForm($this);
  6.  
  7.         // ...
  8.     }
  9. }

Of course, if you can do that... you could and should simply alter the class to inherit from Zend_Dojo_Form, which is a drop-in replacement of Zend_Form that's already Dojo-enabled...

Copyright

© 2006-2021 by Zend by Perforce. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.

Contacts