Bâtie sur les
aides de vues dijit, la famille des classes
Zend_Dojo_Form
fournit la possibilité d'utiliser les Dijits
nativement dans vos formulaires.
Il existe trois options pour utiliser les éléments de formulaires Dojo avec vos formulaires :
-
Utilisez
Zend_Dojo::enableForm()
. Ceci ajoutera, de manière récursive, les chemins de plugin des éléments et des décorateurs pour tous les éléments de formulaires attachés. De plus, ceci active dojo dans l'objet de vue. Notez, cependant, que tout sous-formulaire que vous attacherez après cet appel devront eux aussi faire leur appel àZend_Dojo::enableForm()
. -
Utilisez les implémentations de formulaires et sous-formulaires spécifiques à Dojo, respectivement
Zend_Dojo_Form
etZend_Dojo_Form_SubForm
. Ceux-ci peuvent être utilisés en lieu et place deZend_Form
etZend_Form_SubForm
, ils contiennent tous les chemins appropriés des éléments et décorateurs, ils paramètrent une classe par défaut pour les DisplayGroup spécifique à Dojo et activent dojo dans l'objet de vue. -
En dernier, et le plus pénible, vous pouvez régler vous même les chemins appropriés vers les décorateurs et les éléments, régler la classe de DisplayGroup par défaut, et activer dojo dans l'objet de vue. Puisque
Zend_Dojo::enableForm()
fait déjà ceci, il n'y a que peu de raisons d'utiliser cette voie.
Exemple 354. Activation de Dojo dans vos formulaires existants
"Mais attendez," vous allez me dire ; "j'étends déjà
Zend_Form
avec ma propre classe de formulaire
personnalisé ! Comment puis-je activer Dojo ?'"
Premièrement, et sans doute le plus simple, étendez
Zend_Dojo_Form
au lieu de Zend_Form
, et
mettez à jour tous les endroits où vous intanciez
Zend_Form_SubForm
en le remplaçant par
Zend_Dojo_Form_SubForm
.
Une seconde approche consiste en un appel à
Zend_Dojo::enableForm()
dans la méthode init()
de
vos formulaires ; quand la définition du formulaire est complète, bouclez à travers
tous les sous-formulaires pour y activer dojo pour chacun :
class My_Form_Custom extends Zend_Form { public function init() { // Activer Dojo pour le formulaire : Zend_Dojo::enableForm($this); // ... continuez la définition du formulaire ici // Activer Dojo pour tous les formulaires : foreach ($this->getSubForms() as $subForm) { Zend_Dojo::enableForm($subForm); } } }
L'utilisation des éléments de formulaires et les décorateurs spécifiques à Dijit est identique à l'utilisation de tous autres éléments de formulaires ou décorateurs.
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.
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.
Exemple 355. DijitElement Decorator Usage
$element->setDecorators(array( 'DijitElement', 'Errors', 'Label', 'ContentPane', ));
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.
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
Exemple 356. DijitContainer Decorator Usage
// Use a TabContainer for your form: $form->setDecorators(array( 'FormElements', array('TabContainer', array( 'id' => 'tabContainer', 'style' => 'width: 600px; height: 500px;', 'dijitParams' => array( 'tabPosition' => 'top' ), )), 'DijitForm', )); // Use a ContentPane in your sub form (which can be used with all but // AccordionContainer): $subForm->setDecorators(array( 'FormElements', array('HtmlTag', array('tag' => 'dl')), 'ContentPane', ));
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, returnTRUE
, otherwise returnFALSE
. -
getDijitParam($key)
: retrieve the given dijit parameter. If not available, aNULL
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:
$element->addDecorator('DijitElement') ->addDecorator('Errors') ->addDecorator('HtmlTag', array('tag' => 'dd')) ->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.
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 returnsTRUE
. 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.
Exemple 357. Example Button dijit element usage
$form->addElement( 'Button', 'foo', array( 'label' => 'Button Label', ) );
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.
Exemple 358. Example CheckBox dijit element usage
$form->addElement( 'CheckBox', 'foo', array( 'label' => 'A check box', 'checkedValue' => 'foo', 'uncheckedValue' => 'bar', 'checked' => true, ) );
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.
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.
Exemple 359. ComboBox dijit element usage as select input
$form->addElement( 'ComboBox', 'foo', array( 'label' => 'ComboBox (select)', 'value' => 'blue', 'autocomplete' => false, 'multiOptions' => array( 'red' => 'Rouge', 'blue' => 'Bleu', 'white' => 'Blanc', 'orange' => 'Orange', 'black' => 'Noir', 'green' => 'Vert', ), ) );
Exemple 360. ComboBox dijit element usage with datastore
$form->addElement( 'ComboBox', 'foo', array( 'label' => 'ComboBox (datastore)', 'storeId' => 'stateStore', 'storeType' => 'dojo.data.ItemFileReadStore', 'storeParams' => array( 'url' => '/js/states.txt', ), 'dijitParams' => array( 'searchAttr' => 'name', ), ) );
The above examples could also utilize FilteringSelect
instead of ComboBox
.
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.
Exemple 361. Example CurrencyTextBox dijit element usage
$form->addElement( 'CurrencyTextBox', 'foo', array( 'label' => 'Currency:', 'required' => true, 'currency' => 'USD', 'invalidMessage' => 'Invalid amount. ' . 'Include dollar sign, commas, and cents.', 'fractional' => false, ) );
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)
andgetAmPm()
: Whether or not to use AM or PM strings in times. -
setStrict($flag)
andgetStrict()
: whether or not to use strict regular expression matching when validating input. IfFALSE
, which is the default, it will be lenient about whitespace and some abbreviations. -
setLocale($locale)
andgetLocale()
: Set and retrieve the locale to use with this specific element. -
setDatePattern($pattern)
andgetDatePattern()
: provide and retrieve the unicode date format pattern for formatting the date. -
setFormatLength($formatLength)
andgetFormatLength()
: provide and retrieve the format length type to use; should be one of "long", "short", "medium" or "full". -
setSelector($selector)
andgetSelector()
: provide and retrieve the style of selector; should be either "date" or "time".
Exemple 362. Example DateTextBox dijit element usage
$form->addElement( 'DateTextBox', 'foo', array( 'label' => 'Date:', 'required' => true, 'invalidMessage' => 'Invalid date specified.', 'formatLength' => 'long', ) );
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, whilegetEditActionInterval()
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 methodsetFocusOnLoad($flag)
may be used to set the value, whilegetFocusOnLoad()
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, whilegetHeight()
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 methodsetInheritWidth($flag)
may be used to set the value, whilegetInheritWidth()
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, whilegetMinHeight()
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()
-
Exemple 363. Example Editor dijit element usage
$form->addElement('editor', 'content', array( 'plugins' => array('undo', '|', 'bold', 'italic'), 'editActionInterval' => 2, 'focusOnLoad' => true, 'height' => '250px', 'inheritWidth' => true, 'styleSheets' => array('/js/custom/editor.css'), ));
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
:
// At instantiation: $editor = new Zend_Dojo_Form_Element_Editor('foo', array( 'degrade' => true, )); // Construction via the form: $form->addElement('editor', 'content', array( 'degrade' => true, )); // Or after instantiation: $editor->degrade = true;
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)
andsetBottomDecorationDijit($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)
andsetBottomDecorationContainer($container)
: specify the name to use for the container element of the rules; e.g. 'topRule', 'topContainer', etc. -
setTopDecorationLabels(array $labels)
andsetBottomDecorationLabels(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)
andsetBottomDecorationParams(array $params)
: dijit parameters to use when configuring the given Rule or RuleLabels dijit. -
setTopDecorationAttribs(array $attribs)
andsetBottomDecorationAttribs(array $attribs)
: HTML attributes to specify for the given Rule or RuleLabels HTML element container. -
getTopDecoration()
andgetBottomDecoration()
: retrieve all metadata for a given Rule or RuleLabels definition, as provided by the above mutators.
Exemple 364. 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.
$form->addElement( 'HorizontalSlider', 'horizontal', array( 'label' => 'HorizontalSlider', 'value' => 5, 'minimum' => -10, 'maximum' => 10, 'discreteValues' => 11, 'intermediateChanges' => true, 'showButtons' => true, 'topDecorationDijit' => 'HorizontalRuleLabels', 'topDecorationContainer' => 'topContainer', 'topDecorationLabels' => array( ' ', '20%', '40%', '60%', '80%', ' ', ), 'topDecorationParams' => array( 'container' => array( 'style' => 'height:1.2em; font-size=75%;color:gray;', ), 'list' => array( 'style' => 'height:1em; font-size=75%;color:gray;', ), ), 'bottomDecorationDijit' => 'HorizontalRule', 'bottomDecorationContainer' => 'bottomContainer', 'bottomDecorationLabels' => array( '0%', '50%', '100%', ), 'bottomDecorationParams' => array( 'list' => array( 'style' => 'height:1em; font-size=75%;color:gray;', ), ), ) );
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)
andgetDefaultTimeout()
: set and retrieve the default timeout, in milliseconds, between when the button is held pressed and the value is changed. -
setTimeoutChangeRate($rate)
andgetTimeoutChangeRate()
: set and retrieve the rate, in milliseconds, at which changes will be made when a button is held pressed. -
setLargeDelta($delta)
andgetLargeDelta()
: set and retrieve the amount by which the numeric value should change when a button is held pressed. -
setSmallDelta($delta)
andgetSmallDelta()
: set and retrieve the delta by which the number should change when a button is pressed once. -
setIntermediateChanges($flag)
andgetIntermediateChanges()
: set and retrieve the flag indicating whether or not each value change should be shown when a button is held pressed. -
setRangeMessage($message)
andgetRangeMessage()
: set and retrieve the message indicating the range of values available. -
setMin($value)
andgetMin()
: set and retrieve the minimum value possible. -
setMax($value)
andgetMax()
: set and retrieve the maximum value possible.
Exemple 365. Example NumberSpinner dijit element usage
$form->addElement( 'NumberSpinner', 'foo', array( 'value' => '7', 'label' => 'NumberSpinner', 'smallDelta' => 5, 'largeDelta' => 25, 'defaultTimeout' => 500, 'timeoutChangeRate' => 100, 'min' => 9, 'max' => 1550, 'places' => 0, 'maxlength' => 20, ) );
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)
andgetLocale()
: specify and retrieve a specific or alternate locale to use with this dijit. -
setPattern($pattern)
andgetPattern()
: set and retrieve a number pattern format to use to format the number. -
setType($type)
andgetType()
: set and retrieve the numeric format type to use (should be one of 'decimal', 'percent', or 'currency'). -
setPlaces($places)
andgetPlaces()
: set and retrieve the number of decimal places to support. -
setStrict($flag)
andgetStrict()
: set and retrieve the value of the strict flag, which indicates how much leniency is allowed in relation to whitespace and non-numeric characters.
Exemple 366. Example NumberTextBox dijit element usage
$form->addElement( 'NumberTextBox', 'elevation', array( 'label' => 'NumberTextBox', 'required' => true, 'invalidMessage' => 'Invalid elevation.', 'places' => 0, 'constraints' => array( 'min' => -20000, 'max' => 20000, ), ) );
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.
Exemple 367. Example PasswordTextBox dijit element usage
$form->addElement( 'PasswordTextBox', 'password', array( 'label' => 'Password', 'required' => true, 'trim' => true, 'lowercase' => true, 'regExp' => '^[a-z0-9]{6,}$', 'invalidMessage' => 'Invalid password; ' . 'must be at least 6 alphanumeric characters', ) );
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.
Exemple 368. Example RadioButton dijit element usage
$form->addElement( 'RadioButton', 'foo', array( 'label' => 'RadioButton', 'multiOptions' => array( 'foo' => 'Foo', 'bar' => 'Bar', 'baz' => 'Baz', ), 'value' => 'bar', ) );
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
Exemple 369. Example SimpleTextarea dijit element usage
$form->addElement( 'SimpleTextarea', 'simpletextarea', array( 'label' => 'SimpleTextarea', 'required' => true, 'style' => 'width: 80em; height: 25em;', ) );
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)
andgetClickSelect()
: set and retrieve the flag indicating whether or not clicking the slider changes the value. -
setIntermediateChanges($flag)
andgetIntermediateChanges()
: set and retrieve the flag indicating whether or not the dijit will send a notification on each slider change event. -
setShowButtons($flag)
andgetShowButtons()
: 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)
andgetDiscreteValues()
: set and retrieve the number of discrete values represented by the slider. -
setMaximum($value)
andgetMaximum()
: set the maximum value of the slider. -
setMinimum($value)
andgetMinimum()
: set the minimum value of the slider. -
setPageIncrement($value)
andgetPageIncrement()
: set the amount by which the slider will change on keyboard events.
Example usage is provided with each concrete extending class.
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.
Exemple 370. Example SubmitButton dijit element usage
$form->addElement( 'SubmitButton', 'foo', array( 'required' => false, 'ignore' => true, 'label' => 'Submit Button!', ) );
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)
andgetLowercase()
: set and retrieve the flag indicating whether or not input should be cast to lowercase. -
setPropercase($flag)
andgetPropercase()
: set and retrieve the flag indicating whether or not the input should be cast to Proper Case. -
setUppercase($flag)
andgetUppercase()
: set and retrieve the flag indicating whether or not the input should be cast to UPPERCASE. -
setTrim($flag)
andgetTrim()
: set and retrieve the flag indicating whether or not leading or trailing whitespace should be stripped. -
setMaxLength($length)
andgetMaxLength()
: set and retrieve the maximum length of input.
Exemple 371. Example TextBox dijit element usage
$form->addElement( 'TextBox', 'foo', array( 'value' => 'some text', 'label' => 'TextBox', 'trim' => true, 'propercase' => true, ) );
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.
Exemple 372. Example Textarea dijit element usage
$form->addElement( 'Textarea', 'textarea', array( 'label' => 'Textarea', 'required' => true, 'style' => 'width: 200px;', ) );
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)
andgetTimePattern()
: set and retrieve the unicode time format pattern for formatting the time. -
setClickableIncrement($format)
andgetClickableIncrement()
: set the ISO_8601 string representing the amount by which every clickable element in the time picker increases. -
setVisibleIncrement($format)
andgetVisibleIncrement()
: set the increment visible in the time chooser; must followISO_8601
formats. -
setVisibleRange($format)
andgetVisibleRange()
: set and retrieve the range of time visible in the time chooser at any given moment; must followISO_8601
formats.
Exemple 373. Example TimeTextBox dijit element usage
The following will create a TimeTextBox that displays 2 hours at a time, with increments of 10 minutes.
$form->addElement( 'TimeTextBox', 'foo', array( 'label' => 'TimeTextBox', 'required' => true, 'visibleRange' => 'T04:00:00', 'visibleIncrement' => 'T00:10:00', 'clickableIncrement' => 'T00:10:00', ) );
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)
andgetInvalidMessage()
: set and retrieve the tooltip message to display when the value does not validate. -
setPromptMessage($message)
andgetPromptMessage()
: set and retrieve the tooltip message to display for element usage. -
setRegExp($regexp)
andgetRegExp()
: 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)
andgetConstraint($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)
andgetConstraints()
: 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)
andclearConstraints()
: remove an individual or all constraints for the element.
Exemple 374. 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).
$form->addElement( 'ValidationTextBox', 'foo', array( 'label' => 'ValidationTextBox', 'required' => true, 'regExp' => '[\w]+', 'invalidMessage' => 'Invalid non-space text.', ) );
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.
Exemple 375. 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.
$form->addElement( 'VerticalSlider', 'foo', array( 'label' => 'VerticalSlider', 'value' => 5, 'style' => 'height: 200px; width: 3em;', 'minimum' => -10, 'maximum' => 10, 'discreteValues' => 11, 'intermediateChanges' => true, 'showButtons' => true, 'leftDecorationDijit' => 'VerticalRuleLabels', 'leftDecorationContainer' => 'leftContainer', 'leftDecorationLabels' => array( ' ', '20%', '40%', '60%', '80%', ' ', ), 'rightDecorationDijit' => 'VerticalRule', 'rightDecorationContainer' => 'rightContainer', 'rightDecorationLabels' => array( '0%', '50%', '100%', ), ) );
Exemple 376. 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.
class My_Form_Test extends Zend_Dojo_Form { /** * Options to use with select elements */ protected $_selectOptions = array( 'red' => 'Rouge', 'blue' => 'Bleu', 'white' => 'Blanc', 'orange' => 'Orange', 'black' => 'Noir', 'green' => 'Vert', ); /** * Form initialization * * @return void */ public function init() { $this->setMethod('post'); $this->setAttribs(array( 'name' => 'masterForm', )); $this->setDecorators(array( 'FormElements', array('TabContainer', array( 'id' => 'tabContainer', 'style' => 'width: 600px; height: 500px;', 'dijitParams' => array( 'tabPosition' => 'top' ), )), 'DijitForm', )); $textForm = new Zend_Dojo_Form_SubForm(); $textForm->setAttribs(array( 'name' => 'textboxtab', 'legend' => 'Text Elements', 'dijitParams' => array( 'title' => 'Text Elements', ), )); $textForm->addElement( 'TextBox', 'textbox', array( 'value' => 'some text', 'label' => 'TextBox', 'trim' => true, 'propercase' => true, ) ) ->addElement( 'DateTextBox', 'datebox', array( 'value' => '2008-07-05', 'label' => 'DateTextBox', 'required' => true, ) ) ->addElement( 'TimeTextBox', 'timebox', array( 'label' => 'TimeTextBox', 'required' => true, ) ) ->addElement( 'CurrencyTextBox', 'currencybox', array( 'label' => 'CurrencyTextBox', 'required' => true, // 'currency' => 'USD', 'invalidMessage' => 'Invalid amount. ' . 'Include dollar sign, commas, ' . 'and cents.', // 'fractional' => true, // 'symbol' => 'USD', // 'type' => 'currency', ) ) ->addElement( 'NumberTextBox', 'numberbox', array( 'label' => 'NumberTextBox', 'required' => true, 'invalidMessage' => 'Invalid elevation.', 'constraints' => array( 'min' => -20000, 'max' => 20000, 'places' => 0, ) ) ) ->addElement( 'ValidationTextBox', 'validationbox', array( 'label' => 'ValidationTextBox', 'required' => true, 'regExp' => '[\w]+', 'invalidMessage' => 'Invalid non-space text.', ) ) ->addElement( 'Textarea', 'textarea', array( 'label' => 'Textarea', 'required' => true, 'style' => 'width: 200px;', ) ); $editorForm = new Zend_Dojo_Form_SubForm(); $editorForm->setAttribs(array( 'name' => 'editortab', 'legend' => 'Editor', 'dijitParams' => array( 'title' => 'Editor' ), )) $editorForm->addElement( 'Editor', 'wysiwyg', array( 'label' => 'Editor', 'inheritWidth' => 'true', ) ); $toggleForm = new Zend_Dojo_Form_SubForm(); $toggleForm->setAttribs(array( 'name' => 'toggletab', 'legend' => 'Toggle Elements', )); $toggleForm->addElement( 'NumberSpinner', 'ns', array( 'value' => '7', 'label' => 'NumberSpinner', 'smallDelta' => 5, 'largeDelta' => 25, 'defaultTimeout' => 1000, 'timeoutChangeRate' => 100, 'min' => 9, 'max' => 1550, 'places' => 0, 'maxlength' => 20, ) ) ->addElement( 'Button', 'dijitButton', array( 'label' => 'Button', ) ) ->addElement( 'CheckBox', 'checkbox', array( 'label' => 'CheckBox', 'checkedValue' => 'foo', 'uncheckedValue' => 'bar', 'checked' => true, ) ) ->addElement( 'RadioButton', 'radiobutton', array( 'label' => 'RadioButton', 'multiOptions' => array( 'foo' => 'Foo', 'bar' => 'Bar', 'baz' => 'Baz', ), 'value' => 'bar', ) ); $selectForm = new Zend_Dojo_Form_SubForm(); $selectForm->setAttribs(array( 'name' => 'selecttab', 'legend' => 'Select Elements', )); $selectForm->addElement( 'ComboBox', 'comboboxselect', array( 'label' => 'ComboBox (select)', 'value' => 'blue', 'autocomplete' => false, 'multiOptions' => $this->_selectOptions, ) ) ->addElement( 'ComboBox', 'comboboxremote', array( 'label' => 'ComboBox (remoter)', 'storeId' => 'stateStore', 'storeType' => 'dojo.data.ItemFileReadStore', 'storeParams' => array( 'url' => '/js/states.txt', ), 'dijitParams' => array( 'searchAttr' => 'name', ), ) ) ->addElement( 'FilteringSelect', 'filterselect', array( 'label' => 'FilteringSelect (select)', 'value' => 'blue', 'autocomplete' => false, 'multiOptions' => $this->_selectOptions, ) ) ->addElement( 'FilteringSelect', 'filterselectremote', array( 'label' => 'FilteringSelect (remoter)', 'storeId' => 'stateStore', 'storeType' => 'dojo.data.ItemFileReadStore', 'storeParams' => array( 'url' => '/js/states.txt', ), 'dijitParams' => array( 'searchAttr' => 'name', ), ) ); $sliderForm = new Zend_Dojo_Form_SubForm(); $sliderForm->setAttribs(array( 'name' => 'slidertab', 'legend' => 'Slider Elements', )); $sliderForm->addElement( 'HorizontalSlider', 'horizontal', array( 'label' => 'HorizontalSlider', 'value' => 5, 'minimum' => -10, 'maximum' => 10, 'discreteValues' => 11, 'intermediateChanges' => true, 'showButtons' => true, 'topDecorationDijit' => 'HorizontalRuleLabels', 'topDecorationContainer' => 'topContainer', 'topDecorationLabels' => array( ' ', '20%', '40%', '60%', '80%', ' ', ), 'topDecorationParams' => array( 'container' => array( 'style' => 'height:1.2em; ' . 'font-size=75%;color:gray;', ), 'list' => array( 'style' => 'height:1em; ' . 'font-size=75%;color:gray;', ), ), 'bottomDecorationDijit' => 'HorizontalRule', 'bottomDecorationContainer' => 'bottomContainer', 'bottomDecorationLabels' => array( '0%', '50%', '100%', ), 'bottomDecorationParams' => array( 'list' => array( 'style' => 'height:1em; ' . 'font-size=75%;color:gray;', ), ), ) ) ->addElement( 'VerticalSlider', 'vertical', array( 'label' => 'VerticalSlider', 'value' => 5, 'style' => 'height: 200px; width: 3em;', 'minimum' => -10, 'maximum' => 10, 'discreteValues' => 11, 'intermediateChanges' => true, 'showButtons' => true, 'leftDecorationDijit' => 'VerticalRuleLabels', 'leftDecorationContainer' => 'leftContainer', 'leftDecorationLabels' => array( ' ', '20%', '40%', '60%', '80%', ' ', ), 'rightDecorationDijit' => 'VerticalRule', 'rightDecorationContainer' => 'rightContainer', 'rightDecorationLabels' => array( '0%', '50%', '100%', ), ) ); $this->addSubForm($textForm, 'textboxtab') ->addSubForm($editorForm, 'editortab') ->addSubForm($toggleForm, 'toggletab') ->addSubForm($selectForm, 'selecttab') ->addSubForm($sliderForm, 'slidertab'); } }
Exemple 377. 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:
$form = new My_Custom_Form(); Zend_Dojo::enableForm($form); $form->addElement( 'ComboBox', 'query', array( 'label' => 'Color:', 'value' => 'blue', 'autocomplete' => false, 'multiOptions' => array( 'red' => 'Rouge', 'blue' => 'Bleu', 'white' => 'Blanc', 'orange' => 'Orange', 'black' => 'Noir', 'green' => 'Vert', ), ) );
Alternately, you can make a slight tweak to your form initialization:
class My_Custom_Form extends Zend_Form { public function init() { Zend_Dojo::enableForm($this); // ... } }
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...