Zend_Dojo_Data: dojo.data Envelopes

Les aides de vues Dojo

Zend Framework fournit les aides de vues spécifiques à Dojo suivantes :

  • dojo(): paramètre l'environnement Dojo de votre page, incluant les valeurs de configuration dojo, les chemins de modules personnalisés, les appels de chargement des modules requis, les feuilles de styles des thêmes, l'utilisation ou non d'un CDN, et d'autres encore.

Example #1 Utilisation des aides de vues Dojo

Pour utiliser les aides de vues Dojo, vous devrez informer votre objet de vue de leur localisation. Vous pouvez faire ceci en appelant addHelperPath() :

  1. $view->addHelperPath('Zend/Dojo/View/Helper/',
  2.                      'Zend_Dojo_View_Helper');

De manière alternative, vous pouvez utiliser la méthode enableView() de Zend_Dojo qui le fait pour vous :

  1. Zend_Dojo::enableView($view);

dojo() View Helper

The dojo() view helper is intended to simplify setting up the Dojo environment, including the following responsibilities:

  • Specifying either a CDN or a local path to a Dojo install.

  • Specifying paths to custom Dojo modules.

  • Specifying dojo.require statements.

  • Specifying dijit stylesheet themes to use.

  • Specifying dojo.addOnLoad() events.

The dojo() view helper implementation is an example of a placeholder implementation. The data set in it persists between view objects and may be directly echoed from your layout script.

Example #2 dojo() View Helper Usage Example

For this example, let's assume the developer will be using Dojo from a local path, will require several dijits, and will be utilizing the Tundra dijit theme.

On many pages, the developer may not utilize Dojo at all. So, we will first focus on a view script where Dojo is needed and then on the layout script, where we will setup some of the Dojo environment and then render it.

First, we need to tell our view object to use the Dojo view helper paths. This can be done in your bootstrap or an early-running plugin; simply grab your view object and execute the following:

  1. $view->addHelperPath('Zend/Dojo/View/Helper/', 'Zend_Dojo_View_Helper');

Next, the view script. In this case, we're going to specify that we will be using a FilteringSelect -- which will consume a custom store based on QueryReadStore, which we'll call 'PairedStore' and store in our 'custom' module.

  1. <?php // setup data store for FilteringSelect ?>
  2. <div dojoType="custom.PairedStore" jsId="stateStore"
  3.     url="/data/autocomplete/type/state/format/ajax"
  4.     requestMethod="get"></div>
  5.  
  6. <?php // Input element: ?>
  7. State: <input id="state" dojoType="dijit.form.FilteringSelect"
  8.     store="stateStore" pageSize="5" />
  9.  
  10. <?php // setup required dojo elements:
  11. $this->dojo()->enable()
  12.              ->setDjConfigOption('parseOnLoad', true)
  13.              ->registerModulePath('custom', '../custom/')
  14.              ->requireModule('dijit.form.FilteringSelect')
  15.              ->requireModule('custom.PairedStore'); ?>

In our layout script, we'll then check to see if Dojo is enabled, and, if so, we'll do some more general configuration and assemble it:

  1. <?php echo $this->doctype() ?>
  2. <html>
  3. <head>
  4.     <?php echo $this->headTitle() ?>
  5.     <?php echo $this->headMeta() ?>
  6.     <?php echo $this->headLink() ?>
  7.     <?php echo $this->headStyle() ?>
  8. <?php if ($this->dojo()->isEnabled()){
  9.     $this->dojo()->setLocalPath('/js/dojo/dojo.js')
  10.                  ->addStyleSheetModule('dijit.themes.tundra');
  11.     echo $this->dojo();
  12.    }
  13. ?>
  14.     <?php echo $this->headScript() ?>
  15. </head>
  16. <body class="tundra">
  17.     <?php echo $this->layout()->content ?>
  18.     <?php echo $this->inlineScript() ?>
  19. </body>
  20. </html>

At this point, you only need to ensure that your files are in the correct locations and that you've created the end point action for your FilteringSelect!

Note: UTF-8 encoding used by default
By default, Zend Framework uses UTF-8 as its default encoding, and, specific to this case, Zend_View does as well. Character encoding can be set differently on the view object itself using the setEncoding() method (or the encoding instantiation parameter). However, since Zend_View_Interface does not define accessors for encoding, it's possible that if you are using a custom view implementation with the Dojo view helper, you will not have a getEncoding() method, which is what the view helper uses internally for determining the character set in which to encode.
If you do not want to utilize UTF-8 in such a situation, you will need to implement a getEncoding() method in your custom view implementation.

Programmatic and Declarative Usage of Dojo

Dojo allows both declarative and programmatic usage of many of its features. Declarative usage uses standard HTML elements with non-standard attributes that are parsed when the page is loaded. While this is a powerful and simple syntax to utilize, for many developers this can cause issues with page validation.

Programmatic usage allows the developer to decorate existing elements by pulling them by ID or CSS selectors and passing them to the appropriate object constructors in Dojo. Because no non-standard HTML attributes are used, pages continue to validate.

In practice, both use cases allow for graceful degradation when javascript is disabled or the various Dojo script resources are unreachable. To promote standards and document validation, Zend Framework uses programmatic usage by default; the various view helpers will generate javascript and push it to the dojo() view helper for inclusion when rendered.

Developers using this technique may also wish to explore the option of writing their own programmatic decoration of the page. One benefit would be the ability to specify handlers for dijit events.

To allow this, as well as the ability to use declarative syntax, there are a number of static methods available to set this behavior globally.

Example #3 Specifying Declarative and Programmatic Dojo Usage

To specify declarative usage, simply call the static setUseDeclarative() method:

  1. Zend_Dojo_View_Helper_Dojo::setUseDeclarative();

If you decide instead to use programmatic usage, call the static setUseProgrammatic() method:

  1. Zend_Dojo_View_Helper_Dojo::setUseProgrammatic();

Finally, if you want to create your own programmatic rules, you should specify programmatic usage, but pass in the value '-1'; in this situation, no javascript for decorating any dijits used will be created.

  1. Zend_Dojo_View_Helper_Dojo::setUseProgrammatic(-1);

Themes

Dojo allows the creation of themes for its dijits (widgets). You may select one by passing in a module path:

  1. $view->dojo()->addStylesheetModule('dijit.themes.tundra');

The module path is discovered by using the character '.' as a directory separator and using the last value in the list as the name of the CSS file in that theme directory to use; in the example above, Dojo will look for the theme in 'dijit/themes/tundra/tundra.css'.

When using a theme, it is important to remember to pass the theme class to, at the least, a container surrounding any dijits you are using; the most common use case is to pass it in the body:

  1. <body class="tundra">

Using Layers (Custom Builds)

By default, when you use a dojo.require statement, dojo will make a request back to the server to grab the appropriate javascript file. If you have many dijits in place, this results in many requests to the server -- which is not optimal.

Dojo's answer to this is to provide the ability to create custom builds. Builds do several things:

  • Groups required files into layers; a layer lumps all required files into a single JS file. (Hence the name of this section.)

  • "Interns" non-javascript files used by dijits (typically, template files). These are also grouped in the same JS file as the layer.

  • Passes the file through ShrinkSafe, which strips whitespace and comments, as well as shortens variable names.

Some files can not be layered, but the build process will create a special release directory with the layer file and all other files. This allows you to have a slimmed-down distribution customized for your site or application needs.

To use a layer, the dojo() view helper has a addLayer() method for adding paths to required layers:

  1. $view->dojo()->addLayer('/js/foo/foo.js');

For more information on creating custom builds, please » refer to the Dojo build documentation.

Methods Available

The dojo() view helper always returns an instance of the dojo placeholder container. That container object has the following methods available:

  • setView(Zend_View_Interface $view): set a view instance in the container.

  • enable(): explicitly enable Dojo integration.

  • disable(): disable Dojo integration.

  • isEnabled(): determine whether or not Dojo integration is enabled.

  • requireModule($module): setup a dojo.require statement.

  • getModules(): determine what modules have been required.

  • registerModulePath($module, $path): register a custom Dojo module path.

  • getModulePaths(): get list of registered module paths.

  • addLayer($path): add a layer (custom build) path to use.

  • getLayers(): get a list of all registered layer paths (custom builds).

  • removeLayer($path): remove the layer that matches $path from the list of registered layers (custom builds).

  • setCdnBase($url): set the base URL for a CDN; typically, one of the Zend_Dojo::CDN_BASE_AOL or Zend_Dojo::CDN_BASE_GOOGLE, but it only needs to be the URL string prior to the version number.

  • getCdnBase(): retrieve the base CDN url to utilize.

  • setCdnVersion($version = null): set which version of Dojo to utilize from the CDN.

  • getCdnVersion(): retrieve what version of Dojo from the CDN will be used.

  • setCdnDojoPath($path): set the relative path to the dojo.js or dojo.xd.js file on a CDN; typically, one of the Zend_Dojo::CDN_DOJO_PATH_AOL or Zend_Dojo::CDN_DOJO_PATH_GOOGLE, but it only needs to be the path string following the version number.

  • getCdnDojoPath(): retrieve the last path segment of the CDN url pointing to the dojo.js file.

  • useCdn(): tell the container to utilize the CDN; implicitly enables integration.

  • setLocalPath($path): tell the container the path to a local Dojo install (should be a path relative to the server, and contain the dojo.js file itself); implicitly enables integration.

  • getLocalPath(): determine what local path to Dojo is being used.

  • useLocalPath(): is the integration utilizing a Dojo local path?

  • setDjConfig(array $config): set dojo or dijit configuration values (expects assoc array).

  • setDjConfigOption($option, $value): set a single dojo or dijit configuration value.

  • getDjConfig(): get all dojo or dijit configuration values.

  • getDjConfigOption($option, $default = null): get a single dojo or dijit configuration value.

  • addStylesheetModule($module): add a stylesheet based on a module theme.

  • getStylesheetModules(): get stylesheets registered as module themes.

  • addStylesheet($path): add a local stylesheet for use with Dojo.

  • getStylesheets(): get local Dojo stylesheets.

  • addOnLoad($spec, $function = null): add a lambda for dojo.onLoad to call. If one argument is passed, it is assumed to be either a function name or a javascript closure. If two arguments are passed, the first is assumed to be the name of an object instance variable and the second either a method name in that object or a closure to utilize with that object.

  • prependOnLoad($spec, $function = null): exactly like addOnLoad(), excepts prepends to beginning of onLoad stack.

  • getOnLoadActions(): retrieve all dojo.onLoad actions registered with the container. This will be an array of arrays.

  • onLoadCaptureStart($obj = null): capture data to be used as a lambda for dojo.onLoad(). If $obj is provided, the captured JS code will be considered a closure to use with that Javascript object.

  • onLoadCaptureEnd($obj = null): finish capturing data for use with dojo.onLoad().

  • javascriptCaptureStart(): capture arbitrary javascript to be included with Dojo JS (onLoad, require, etc. statements).

  • javascriptCaptureEnd(): finish capturing javascript.

  • __toString(): cast the container to a string; renders all HTML style and script elements.

Dijit-Specific View Helpers

From the Dojo manual: "Dijit is a widget system layered on top of dojo." Dijit includes a variety of layout and form widgets designed to provide accessibility features, localization, and standardized (and themeable) look-and-feel.

Zend Framework ships a variety of view helpers that allow you to render and utilize dijits within your view scripts. There are three basic types:

  • Layout Containers: these are designed to be used within your view scripts or consumed by form decorators for forms, sub forms, and display groups. They wrap the various classes offerred in dijit.layout. Each dijit layout view helper expects the following arguments:

    • $id: the container name or DOM ID.

    • $content: the content to wrap in the layout container.

    • $params (optional): dijit-specific parameters. Basically, any non-HTML attribute that can be used to configure the dijit layout container.

    • $attribs (optional): any additional HTML attributes that should be used to render the container div. If the key 'id' is passed in this array, it will be used for the form element DOM id, and $id will be used for its name.

    If you pass no arguments to a dijit layout view helper, the helper itself will be returned. This allows you to capture content, which is often an easier way to pass content to the layout container. Examples of this functionality will be shown later in this section.

  • Form Dijit: the dijit.form.Form dijit, while not completely necessary for use with dijit form elements, will ensure that if an attempt is made to submit a form that does not validate against client-side validations, submission will be halted and validation error messages raised. The form dijit view helper expects the following arguments:

    • $id: the container name or DOM ID.

    • $attribs (optional): any additional HTML attributes that should be used to render the container div.

    • $content (optional): the content to wrap in the form. If none is passed, an empty string will be used.

    The argument order varies from the other dijits in order to keep compatibility with the standard form() view helper.

  • Form Elements: these are designed to be consumed with Zend_Form, but can be used standalone within view scripts as well. Each dijit element view helper expects the following arguments:

    • $id: the element name or DOM ID.

    • $value (optional): the current value of the element.

    • $params (optional): dijit-specific parameters. Basically, any non-HTML attribute that can be used to configure a dijit.

    • $attribs (optional): any additional HTML attributes that should be used to render the dijit. If the key 'id' is passed in this array, it will be used for the form element DOM id, and $id will be used for its name.

    Some elements require more arguments; these will be noted with the individual element helper descriptions.

In order to utilize these view helpers, you need to register the path to the dojo view helpers with your view object.

Example #4 Registering the Dojo View Helper Prefix Path

  1. $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper');

Dijit Layout Elements

The dijit.layout family of elements are for creating custom, predictable layouts for your site. For any questions on general usage, » read more about them in the Dojo manual.

All dijit layout elements have the signature string ($id = null, $content = '', array $params = array(), array $attribs = array()). In all caess, if you pass no arguments, the helper object itself will be returned. This gives you access to the captureStart() and captureEnd() methods, which allow you to capture content instead of passing it to the layout container.

  • AccordionContainer: dijit.layout.AccordionContainer. Stack all panes together vertically; clicking on a pane titlebar will expand and display that particular pane.

    1. <?php echo $view->accordionContainer(
    2.     'foo',
    3.     $content,
    4.     array(
    5.         'duration' => 200,
    6.     ),
    7.     array(
    8.         'style' => 'width: 200px; height: 300px;',
    9.     ),
    10. ); ?>
  • AccordionPane: dijit.layout.AccordionPane. For use within AccordionContainer.

    1. <?php echo $view->accordionPane(
    2.     'foo',
    3.     $content,
    4.     array(
    5.         'title' => 'Pane Title',
    6.     ),
    7.     array(
    8.         'style' => 'background-color: lightgray;',
    9.     ),
    10. ); ?>
  • BorderContainer: dijit.layout.BorderContainer. Achieve layouts with optionally resizable panes such as you might see in a traditional application.

    1. <?php echo $view->borderContainer(
    2.     'foo',
    3.     $content,
    4.     array(
    5.         'design' => 'headline',
    6.     ),
    7.     array(
    8.         'style' => 'width: 100%; height: 100%',
    9.     ),
    10. ); ?>
  • ContentPane: dijit.layout.ContentPane. Use inside any container except AccordionContainer.

    1. <?php echo $view->contentPane(
    2.     'foo',
    3.     $content,
    4.     array(
    5.         'title'  => 'Pane Title',
    6.         'region' => 'left',
    7.     ),
    8.     array(
    9.         'style' => 'width: 120px; background-color: lightgray;',
    10.     ),
    11. ); ?>
  • SplitContainer: dijit.layout.SplitContainer. Allows resizable content panes; deprecated in Dojo in favor of BorderContainer.

    1. <?php echo $view->splitContainer(
    2.     'foo',
    3.     $content,
    4.     array(
    5.         'orientation'  => 'horizontal',
    6.         'sizerWidth'   => 7,
    7.         'activeSizing' => true,
    8.     ),
    9.     array(
    10.         'style' => 'width: 400px; height: 500px;',
    11.     ),
    12. ); ?>
  • StackContainer: dijit.layout.StackContainer. All panes within a StackContainer are placed in a stack; build buttons or functionality to reveal one at a time.

    1. <?php echo $view->stackContainer(
    2.     'foo',
    3.     $content,
    4.     array(),
    5.     array(
    6.         'style' => 'width: 400px; height: 500px; border: 1px;',
    7.     ),
    8. ); ?>
  • TabContainer: dijit.layout.TabContainer. All panes within a TabContainer are placed in a stack, with tabs positioned on one side for switching between them.

    1. <?php echo $view->tabContainer(
    2.     'foo',
    3.     $content,
    4.     array(),
    5.     array(
    6.         'style' => 'width: 400px; height: 500px; border: 1px;',
    7.     ),
    8. ); ?>

The following capture methods are available for all layout containers:

  • captureStart($id, array $params = array(), array $attribs = array());: begin capturing content to include in a container. $params refers to the dijit params to use with the container, while $attribs refer to any general HTML attributes to use.

    Containers may be nested when capturing, so long as no ids are duplicated.

  • captureEnd($id): finish capturing content to include in a container. $id should refer to an id previously used with a captureStart() call. Returns a string representing the container and its contents, just as if you'd simply passed content to the helper itself.

Example #5 BorderContainer layout dijit example

BorderContainers, particularly when coupled with the ability to capture content, are especially useful for achieving complex layout effects.

  1. $view->borderContainer()->captureStart('masterLayout',
  2.                                        array('design' => 'headline'));
  3.  
  4. echo $view->contentPane(
  5.     'menuPane',
  6.     'This is the menu pane',
  7.     array('region' => 'top'),
  8.     array('style' => 'background-color: darkblue;')
  9. );
  10.  
  11. echo  $view->contentPane(
  12.     'navPane',
  13.     'This is the navigation pane',
  14.     array('region' => 'left'),
  15.     array('style' => 'width: 200px; background-color: lightblue;')
  16. );
  17.  
  18. echo $view->contentPane(
  19.     'mainPane',
  20.     'This is the main content pane area',
  21.     array('region' => 'center'),
  22.     array('style' => 'background-color: white;')
  23. );
  24.  
  25. echo $view->contentPane(
  26.     'statusPane',
  27.     'Status area',
  28.     array('region' => 'bottom'),
  29.     array('style' => 'background-color: lightgray;')
  30. );
  31.  
  32. echo $view->borderContainer()->captureEnd('masterLayout');

Dijit Form Elements

Dojo's form validation and input dijits are in the dijit.form tree. For more information on general usage of these elements, as well as accepted parameters, please » visit the dijit.form documentation.

The following dijit form elements are available in Zend Framework. Except where noted, all have the signature string ($id, $value = '', array $params = array(), array $attribs = array()).

  • Button: dijit.form.Button. Display a form button.

    1. <?php echo $view->button(
    2.     'foo',
    3.     'Show Me!',
    4.     array('iconClass' => 'myButtons'),
    5. ); ?>
  • CheckBox: dijit.form.CheckBox. Display a checkbox. Accepts an optional fifth argument, the array $checkedOptions, which may contain either:

    • an indexed array with two values, a checked value and unchecked value, in that order; or

    • an associative array with the keys 'checkedValue' and 'unCheckedValue'.

    If $checkedOptions is not provided, 1 and 0 are assumed.

    1. <?php echo $view->checkBox(
    2.     'foo',
    3.     'bar',
    4.     array(),
    5.     array(),
    6.     array('checkedValue' => 'foo', 'unCheckedValue' => 'bar')
    7. ); ?>
  • ComboBox: dijit.layout.ComboBox. ComboBoxes are a hybrid between a select and a text box with autocompletion. The key difference is that you may type an option that is not in the list of available options, and it will still consider it valid input. It accepts an optional fifth argument, an associative array $options; if provided, ComboBox will be rendered as a select. Note also that the label values of the $options array will be returned in the form -- not the values themselves.

    Alternately, you may pass information regarding a dojo.data datastore to use with the element. If provided, the ComboBox will be rendered as a text input, and will pull its options via that datastore.

    To specify a datastore, provide one of the following $params key combinations:

    • The key 'store', with an array value; the array should contain the keys:

      • store: the name of the javascript variable representing the datastore (this could be the name you would like for it to use).

      • type: the datastore type to use; e.g., 'dojo.data.ItemFileReadStore'.

      • params (optional): an associative array of key and value pairs to use to configure the datastore. The 'url' param is a typical example.

    • The keys:

      • store: a string indicating the datastore name to use.

      • storeType: a string indicating the datastore dojo.data type to use (e.g., 'dojo.data.ItemFileReadStore').

      • storeParams: an associative array of key and value pairs with which to configure the datastore.

    1. // As a select element:
    2. echo $view->comboBox(
    3.     'foo',
    4.     'bar',
    5.     array(
    6.         'autocomplete' => false,
    7.     ),
    8.     array(),
    9.     array(
    10.         'foo' => 'Foo',
    11.         'bar' => 'Bar',
    12.         'baz' => 'Baz',
    13.     )
    14. );
    15.  
    16. // As a dojo.data-enabled element:
    17. echo $view->comboBox(
    18.     'foo',
    19.     'bar',
    20.     array(
    21.         'autocomplete' => false,
    22.         'store'        => 'stateStore',
    23.         'storeType'    => 'dojo.data.ItemFileReadStore',
    24.         'storeParams'  => array('url' => '/js/states.json'),
    25.     ),
    26. );
  • CurrencyTextBox: dijit.form.CurrencyTextBox. Inherits from ValidationTextBox, and provides client-side validation of currency. It expects that the dijit parameter 'currency' will be provided with an appropriate 3-character currency code. You may also specify any dijit parameters valid for ValidationTextBox and TextBox.

    1. echo $view->currencyTextBox(
    2.     'foo',
    3.     '$25.00',
    4.     array('currency' => 'USD'),
    5.     array('maxlength' => 20)
    6. );

    Note: Issues with Builds
    There are currently » known issues with using CurrencyTextBox with build layers. A known work-around is to ensure that your document's Content-Type http-equiv meta tag sets the character set to utf-8, which you can do by calling:

    1. $view->headMeta()->appendHttpEquiv('Content-Type',
    2.                                    'text/html; charset=utf-8');
    This will mean, of course, that you will need to ensure that the headMeta() placeholder is echoed in your layout script.

  • DateTextBox: dijit.form.DateTextBox. Inherits from ValidationTextBox, and provides both client-side validation of dates, as well as a dropdown calendar from which to select a date. You may specify any dijit parameters available to ValidationTextBox or TextBox.

    1. echo $view->dateTextBox(
    2.     'foo',
    3.     '2008-07-11',
    4.     array('required' => true)
    5. );
  • Editor: dijit.Editor. Provides a WYSIWYG editor via which users may create or edit content. dijit.Editor is a pluggable, extensible editor with a variety of parameters you can utilize for customization; see » the dijit.Editor documentation for more details.

    1. echo $view->editor('foo');

    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.
    In order to allow graceful degradation in environments where Javascript is unavailable, Zend_Dojo_View_Helper_Editor also wraps a TEXTAREA within a NOSCRIPT tag; the content of this TEXTAREA will be properly escaped to avoid security vulnerability vectors.

  • FilteringSelect: dijit.form.FilteringSelect. Similar to ComboBox, this is a select and text hybrid that can either render a provided list of options or those fetched via a dojo.data datastore. Unlike ComboBox, however, FilteringSelect does not allow typing in an option not in its list. Additionally, it operates like a standard select in that the option values, not the labels, are returned when the form is submitted.

    Please see the information above on ComboBox for examples and available options for defining datastores.

  • HorizontalSlider and VerticalSlider: dijit.form.HorizontalSlider and dijit.form.VerticalSlider. Sliders allow are UI widgets for selecting numbers in a given range; these are horizontal and vertical variants.

    At their most basic, they require the dijit parameters 'minimum', 'maximum', and 'discreteValues'. These define the range of values. Other common options are:

    • 'intermediateChanges' can be set to indicate whether or not to fire onChange events while the handle is being dragged.

    • 'clickSelect' can be set to allow clicking a location on the slider to set the value.

    • 'pageIncrement' can specify the value by which to increase or decrease when pageUp and pageDown are used.

    • 'showButtons' can be set to allow displaying buttons on either end of the slider for manipulating the value.

    The implication from Zend Framework creates a hidden element to store the value of the slider.

    You may optionally desire to show a rule or labels for the slider. To do so, you will assign one or more of the dijit params 'topDecoration' and/or 'bottomDecoration' (HorizontalSlider) or 'leftDecoration' and/or 'rightDecoration' (VerticalSlider). Each of these expects the following options:

    • container: name of the container.

    • labels (optional): an array of labels to utilize. Use empty strings on either end to provide labels for inner values only. Required when specifying one of the 'Labels' dijit variants.

    • dijit (optional): one of HorizontalRule, HorizontalRuleLabels, VerticalRule, or VerticalRuleLabels, Defaults to one of the Rule dijits.

    • params (optional): dijit params for configuring the Rule dijit in use. Parameters specific to these dijits include:

      • container (optional): array of parameters and attributes for the rule container.

      • labels (optional): array of parameters and attributes for the labels list container.

    • attribs (optional): HTML attributes to use with the rules and labels. This should follow the params option format and be an associative array with the keys 'container' and 'labels'.

    1. echo $view->horizontalSlider(
    2.     'foo',
    3.     1,
    4.     array(
    5.         'minimum'             => -10,
    6.         'maximum'             => 10,
    7.         'discreteValues'      => 11,
    8.         'intermediateChanges' => true,
    9.         'showButtons'         => true,
    10.         'topDecoration'       => array(
    11.             'container' => 'topContainer'
    12.             'dijit'     => 'HorizontalRuleLabels',
    13.             'labels'    => array(
    14.                 ' ',
    15.                 '20%',
    16.                 '40%',
    17.                 '60%',
    18.                 '80%',
    19.                 ' ',
    20.             ),
    21.             'params' => array(
    22.                 'container' => array(
    23.                     'style' => 'height:1.2em; font-size=75%;color:gray;',
    24.                 ),
    25.                 'labels' => array(
    26.                     'style' => 'height:1em; font-size=75%;color:gray;',
    27.                 ),
    28.             ),
    29.         ),
    30.         'bottomDecoration'    => array(
    31.             'container' => 'bottomContainer'
    32.             'labels'    => array(
    33.                 '0%',
    34.                 '50%',
    35.                 '100%',
    36.             ),
    37.             'params' => array(
    38.                 'container' => array(
    39.                     'style' => 'height:1.2em; font-size=75%;color:gray;',
    40.                 ),
    41.                 'labels' => array(
    42.                     'style' => 'height:1em; font-size=75%;color:gray;',
    43.                 ),
    44.             ),
    45.         ),
    46.     )
    47. );
  • NumberSpinner: dijit.form.NumberSpinner. Text box for numeric entry, with buttons for incrementing and decrementing.

    Expects either an associative array for the dijit parameter 'constraints', or simply the keys 'min', 'max', and 'places' (these would be the expected entries of the constraints parameter as well). 'places' can be used to indicate how much the number spinner will increment and decrement.

    1. echo $view->numberSpinner(
    2.     'foo',
    3.     5,
    4.     array(
    5.         'min'    => -10,
    6.         'max'    => 10,
    7.         'places' => 2,
    8.     ),
    9.     array(
    10.         'maxlenth' => 3,
    11.     )
    12. );
  • NumberTextBox: dijit.form.NumberTextBox. NumberTextBox provides the ability to format and display number entries in a localized fashion, as well as validate numerical entries, optionally against given constraints.

    1. echo $view->numberTextBox(
    2.     'foo',
    3.     5,
    4.     array(
    5.         'places' => 4,
    6.         'type'   => 'percent',
    7.     ),
    8.     array(
    9.         'maxlength' => 20,
    10.     )
    11. );
  • PasswordTextBox: dijit.form.ValidationTextBox tied to a password input. PasswordTextBox provides the ability to create password input that adheres to the current dijit theme, as well as allow for client-side validation.

    1. echo $view->passwordTextBox(
    2.     'foo',
    3.     '',
    4.     array(
    5.         'required' => true,
    6.     ),
    7.     array(
    8.         'maxlength' => 20,
    9.     )
    10. );
  • RadioButton: dijit.form.RadioButton. A set of options from which only one may be selected. This behaves in every way like a regular radio, but has a look-and-feel consistent with other dijits.

    RadioButton accepts an optional fifth argument, $options, an associative array of value and label pairs used as the radio options. You may also pass these as the $attribs key options.

    1. echo $view->radioButton(
    2.     'foo',
    3.     'bar',
    4.     array(),
    5.     array(),
    6.     array(
    7.         'foo' => 'Foo',
    8.         'bar' => 'Bar',
    9.         'baz' => 'Baz',
    10.     )
    11. );
  • SimpleTextarea: dijit.form.SimpleTextarea. These act like normal textareas, but are styled using the current dijit theme. You do not need to specify either the rows or columns attributes; use ems or percentages for the width and height, instead.

    1. echo $view->simpleTextarea(
    2.     'foo',
    3.     'Start writing here...',
    4.     array(),
    5.     array('style' => 'width: 90%; height: 5ems;')
    6. );
  • SubmitButton: a dijit.form.Button tied to a submit input element. See the Button view helper for more details; the key difference is that this button can submit a form.

  • Textarea: dijit.form.Textarea. These act like normal textareas, except that instead of having a set number of rows, they expand as the user types. The width should be specified via a style setting.

    1. echo $view->textarea(
    2.     'foo',
    3.     'Start writing here...',
    4.     array(),
    5.     array('style' => 'width: 300px;')
    6. );
  • TextBox: dijit.form.TextBox. This element is primarily present to provide a common look-and-feel between various dijit elements, and to provide base functionality for the other TextBox-derived classes (ValidationTextBox, NumberTextBox, CurrencyTextBox, DateTextBox, and TimeTextBox).

    Common dijit parameter flags include 'lowercase' (cast to lowercase), 'uppercase' (cast to UPPERCASE), 'propercase' (cast to Proper Case), and trim (trim leading and trailing whitespace); all accept boolean values. Additionally, you may specifiy the parameters 'size' and 'maxLength'.

    1. echo $view->textBox(
    2.     'foo',
    3.     'some text',
    4.     array(
    5.         'trim'       => true,
    6.         'propercase' => true,
    7.         'maxLength'  => 20,
    8.     ),
    9.     array(
    10.         'size' => 20,
    11.     )
    12. );
  • TimeTextBox: dijit.form.TimeTextBox. Also in the TextBox family, TimeTextBox provides a scrollable drop down selection of times from which a user may select. Dijit parameters allow you to specify the time increments available in the select as well as the visible range of times available.

    1. echo $view->timeTextBox(
    2.     'foo',
    3.     '',
    4.     array(
    5.         'am.pm'            => true,
    6.         'visibleIncrement' => 'T00:05:00', // 5-minute increments
    7.         'visibleRange'     => 'T02:00:00', // show 2 hours of increments
    8.     ),
    9.     array(
    10.         'size' => 20,
    11.     )
    12. );
  • ValidationTextBox: dijit.form.ValidateTextBox. Provide client-side validations for a text element. Inherits from TextBox.

    Common dijit parameters include:

    • invalidMessage: a message to display when an invalid entry is detected.

    • promptMessage: a tooltip help message to use.

    • regExp: a regular expression to use to validate the text. Regular expression does not require boundary markers.

    • required: whether or not the element is required. If so, and the element is embedded in a dijit.form.Form, it will be flagged as invalid and prevent submission.

    1. echo $view->validationTextBox(
    2.     'foo',
    3.     '',
    4.     array(
    5.         'required' => true,
    6.         'regExp'   => '[\w]+',
    7.         'invalidMessage' => 'No spaces or non-word characters allowed',
    8.         'promptMessage'  => 'Single word consisting of alphanumeric ' .
    9.                             'characters and underscores only',
    10.     ),
    11.     array(
    12.         'maxlength' => 20,
    13.     )
    14. );

Custom Dijits

If you delve into Dojo much at all, you'll find yourself writing custom dijits, or using experimental dijits from Dojox. While Zend Framework cannot support every dijit directly, it does provide some rudimentary support for arbitrary dijit types via the CustomDijit view helper.

The CustomDijit view helper's API is exactly that of any other dijit, with one major difference: the third "params" argument must contain the attribute "dojotype". The value of this attribute should be the Dijit class you plan to use.

CustomDijit extends the base DijitContainer view helper, which also allows it to capture content (using the captureStart()/ captureEnd() pair of methods). captureStart() also expects that you pass the "dojoType" attribute to its "params" argument.

Example #6 Using CustomDijit to render a dojox.layout.ContentPane

dojox.layout.ContentPane is a next-generation iteration of dijit.layout.ContentPane, and provides a superset of that class's capabilities. Until it's functionality stabilizes, it will continue to live in Dojox. However, if you want to use it in Zend Framework today, you can, using the CustomDijit view helper.

At its most basic, you can do the following:

  1. <?php echo $this->customDijit(
  2.     'foo',
  3.     $content,
  4.     array(
  5.         'dojoType' => 'dojox.layout.ContentPane',
  6.         'title'    => 'Custom pane',
  7.         'region'   => 'center'
  8.     )
  9. ); ?>

If you wanted to capture content instead, simply use the captureStart() method, and pass the "dojoType" to the "params" argument:

  1. <?php $this->customDijit()->captureStart(
  2.     'foo',
  3.     array(
  4.         'dojoType' => 'dojox.layout.ContentPane',
  5.         'title'    => 'Custom pane',
  6.         'region'   => 'center'
  7.     )
  8. ); ?>
  9. This is the content of the pane
  10. <?php echo $this->customDijit()->captureEnd('foo'); ?>

You can also extend CustomDijit easily to create support for your own custom dijits. As an example, if you extended dijit.layout.ContentPane to create your own foo.ContentPane class, you could create the following helper to support it:

  1. class My_View_Helper_FooContentPane
  2.     extends Zend_Dojo_View_Helper_CustomDijit
  3. {
  4.     protected $_defaultDojoType = 'foo.ContentPane';
  5.  
  6.     public function fooContentPane(
  7.         $id = null, $value = null,
  8.         array $params = array(), array $attribs = array()
  9.     ) {
  10.         return $this->customDijit($id, $value, $params, $attribs);
  11.     }
  12. }

As long as your custom dijit follows the same basic API as official dijits, using or extending CustomDijit should work correctly.


Zend_Dojo_Data: dojo.data Envelopes