Dojo ビューヘルパー

Zend Framework は、次のような Dojo 専用ビューヘルパーを用意しています。

  • dojo(): Dojo 環境のセットアップ、つまり dojo の設定やカスタムモジュールのパス、モジュールの require 文、 テーマのスタイルシート、 CDN を使用するか否かなどの指定を行います。

例351 Dojo ビューヘルパーの使用法

Dojo ビューヘルパーを使用するには、 どこを探せばいいのかをビューオブジェクトに教えてやる必要があります。 そのためには addHelperPath() をコールします。

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

あるいは、Zend_DojoenableView() メソッドでそれを行うこともできます。

Zend_Dojo::enableView($view);

dojo() ビューヘルパー

dojo() ビューヘルパーは Dojo 環境のセットアップを簡単に行うためのものです。 次のような機能があります。

  • CDN あるいはローカルパスのどちらの Dojo を使用するかの指定

  • カスタム Dojo モジュールへのパスの指定

  • dojo.require 文の指定

  • 使用する dijit スタイルシートテーマの指定

  • dojo.addOnLoad() イベントの指定

dojo() ビューヘルパーの実装は、 プレースホルダの実装の一例です。 中で扱うデータセットはビューオブジェクトを超えて永続化され、 レイアウトスクリプトから直接 echo できます。

例352 dojo() ビューヘルパーの使用例

この例では、ローカルパスの Dojo を使うことを想定しています。 またいくつかの dijit を使い、Tundra dijit テーマを使用するものとします。

多くのページでは、開発者は Dojo をまったく使用しません。 そこで、Dojo が必要となるビュースクリプトやレイアウトスクリプトだけに注目し、 そこで Dojo 環境を用意してレンダリングすることにします。

まず、ビューオブジェクトに Dojo ビューヘルパーのパスを教えてやる必要があります。 これは、起動ファイルあるいは初期に実行されるプラグインで行います。 ビューオブジェクトを取得して次のコードを実行しましょう。

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

次はビュースクリプトです。今回の例では、 FilteringSelect を使うことにします。 これは QueryReadStore を継承したカスタムストアを使用します。 今回の例ではこれは 'PairedStore' という名前で、 'custom' モジュールに格納します。

<?php // FilteringSelect 用のデータストアの設定 ?>
<div dojoType="custom.PairedStore" jsId="stateStore"
    url="/data/autocomplete/type/state/format/ajax"
    requestMethod="get"></div>

<?php // 入力要素 ?>
State: <input id="state" dojoType="dijit.form.FilteringSelect"
    store="stateStore" pageSize="5" />

<?php // 必須 dojo 要素の設定
$this->dojo()->enable()
             ->setDjConfigOption('parseOnLoad', true)
             ->registerModulePath('custom', '../custom/')
             ->requireModule('dijit.form.FilteringSelect')
             ->requireModule('custom.PairedStore'); ?>

レイアウトスクリプトでは、 まず Dojo が有効になっているかどうかを調べ、 有効ならさらに設定を行ってそれを使用します。

<?php echo $this->doctype() ?>
<html>
<head>
    <?php echo $this->headTitle() ?>
    <?php echo $this->headMeta() ?>
    <?php echo $this->headLink() ?>
    <?php echo $this->headStyle() ?>
<?php if ($this->dojo()->isEnabled()){
    $this->dojo()->setLocalPath('/js/dojo/dojo.js')
                 ->addStyleSheetModule('dijit.themes.tundra');
    echo $this->dojo();
   }
?>
    <?php echo $this->headScript() ?>
</head>
<body class="tundra">
    <?php echo $this->layout()->content ?>
    <?php echo $this->inlineScript() ?>
</body>
</html>

これで、各ファイルが正しい場所にありさえすれば FilteringSelect を使った処理ができるようになりました!


デフォルトで使用される UTF-8 エンコーディング

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

プログラム的および宣言的な Dojo 使用法

Dojo の機能の多くは、宣言的 (declarative) な方法および プログラム的 (programmatic) な方法の両方で使用できます。 宣言的 な使用法とは、 標準の HTML 要素に対して非標準の属性を指定し、 ページの読み込み時にそれをパースするというものです。 これは強力でシンプルな構文のため使用しやすいのですが、 ページの検証時に問題を起こす可能性があります。

プログラム的 な使用法とは、 既存の要素を ID もしくは CSS セレクタで取得し、 それを Dojo の適切なオブジェクトのコンストラクタに渡すというものです。 非標準の HTML 属性を使うことはないので、ページの検証はうまくいきます。

実際のところ、どちらの手法を用いたとしても、 javascript が無効になっていたり Dojo スクリプトリソースが使用できなかったりした場合に機能が低下してしまいます。 標準規格とドキュメントの検証を優先させるため、Zend Framework ではプログラム的な使用法をデフォルトとしています。 さまざまなビューヘルパーが javascript を生成してそれを dojo() ビューヘルパーに渡し、レンダリング時に読み込むのです。

この方法を使うと、さまざまなオプションを使用して プログラム上で独自のデコレーションを行うことができます。 たとえば dijit イベントのハンドラを指定することなども可能です。

そのために、宣言的な構文の機能以外にも多くの静的メソッドが用意されており、 全体の振る舞いを設定できます。

例353 宣言的、あるいはプログラム的な Dojo の使用法の指定

宣言的な使用法を指定するには、静的メソッド setUseDeclarative() をコールします。

Zend_Dojo_View_Helper_Dojo::setUseDeclarative();

プログラム的な使用法を指定するには、静的メソッド setUseProgrammatic() をコールします。

Zend_Dojo_View_Helper_Dojo::setUseProgrammatic();

独自のプログラム的なルールを作成したい場合は、 プログラム的な使用法を指定する際に値 '-1' を渡す必要があります。この場合、 dijit を装飾するための javascript は生成されません。

Zend_Dojo_View_Helper_Dojo::setUseProgrammatic(-1);

テーマ

Dojo では、dijits (widgets) 用のテーマを作成できます。 テーマを選択するにはモジュールパスにそれを渡します。

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

モジュールパスの検索は、'.' をディレクトリ区切り文字として使用し、 リストの最後の名前を CSS ファイルと見て行います。上の例では、Dojo は 'dijit/themes/tundra/tundra.css' のテーマを探します。

テーマを使う際に重要なのは、使用するすべての dijit について、それを囲むコンテナにテーマのクラスを指定することです。 もっともよくある例は、body に指定するものです。

<body class="tundra">

レイヤーの使用 (カスタムビルド)

デフォルトでは、dojo.require ステートメントを使用すると dojo はサーバにリクエストを返し、適切な javascript ファイルを取得します。 たくさんの dijit を使用する場合は、大量のリクエストがサーバに届くことになります。 これはちょっと無駄ですね。

これに対する Dojo からの回答はとして用意したのが カスタムビルド です。これは、次のようなことを行います。

  • 必要なファイルを レイヤー にまとめます。 レイヤーは、すべての必要なファイルをひとつの JS ファイルにまとめたものです (これが、このセクションの名前の由来です)。

  • digit が使用する javascript 以外のファイル (テンプレートファイルなど) をまとめます。 これらもまた、レイヤーとして同じ JS ファイルにまとめられます。

  • そのファイルを ShrinkSafe に渡します。 これは、空白文字やコメントを削除して変数名を短くします。

中にはレイヤー化できないファイルもありますが、 ビルドの際にリリース用のディレクトリが作成され、 レイヤーファイルとその他のすべてのファイルが格納されます。 これにより、あなたの作成するサイトやアプリケーションが 必要とするだけの内容に最適化した内容を配布できます。

レイヤーを使うために、dojo() ビューヘルパーには addLayer() メソッドが用意されており、 これで必要なレイヤーへのパスを追加します。

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

独自のビルドを作成するためのさらなる情報は、 Dojo のビルドのドキュメントを参照ください

使用できるメソッド

dojo() ビューヘルパーは常に、 dojo プレースホルダコンテナのインスタンスを返します。 このコンテナオブジェクトで使用できるメソッドは次のとおりです。

  • setView(Zend_View_Interface $view): コンテナ内のビューインスタンスを設定します。

  • enable(): Dojo 統合機能を明示的に有効化します。

  • disable(): Dojo 統合機能を無効化します。

  • isEnabled(): Dojo 統合機能が有効かどうかを調べます。

  • requireModule($module): dojo.require 文を作成します。

  • getModules(): どのモジュールが必要なのかを調べます。

  • registerModulePath($module, $path): 独自の Dojo モジュールのパスを登録します。

  • getModulePaths(): 登録済みのモジュールパスの一覧を取得します。

  • addLayer($path): 使用するレイヤー (カスタムビルド) のパスを追加します。

  • getLayers(): 登録済みのすべてのレイヤー (カスタムビルド) のパスの一覧を取得します。

  • removeLayer($path): $path にマッチするレイヤー (カスタムビルド) を、 登録済みレイヤーの一覧から削除します。

  • setCdnBase($url): CDN 用のベース URL を設定します。一般的には Zend_Dojo::CDN_BASE_AOL あるいは Zend_Dojo::CDN_BASE_GOOGLE となりますが、これはバージョン番号より前に URL 文字列に必要となります。

  • getCdnBase(): 使用するベース CDNURL を取得します。

  • setCdnVersion($version = null): CDN から使用する Dojo のバージョンを設定します。

  • getCdnVersion(): CDN からどのバージョンの Dojo を使用しているかを取得します。

  • setCdnDojoPath($path): CDN 上のファイル dojo.js あるいは dojo.xd.js への相対パスを設定します。一般的には Zend_Dojo::CDN_DOJO_PATH_AOL あるいは Zend_Dojo::CDN_DOJO_PATH_GOOGLE となりますが、これはバージョン番号の後の URL 文字列に必要となります。

  • getCdnDojoPath(): dojo.js ファイルを指す、CDN url のパスの最後の部分を取得します。

  • useCdn(): コンテナに、CDN を使用するよう指定します。暗黙的に統合機能を有効化します。

  • setLocalPath($path): コンテナに、ローカルの Dojo インストールパスを指定します (サーバからの相対パスで、かつ dojo.js ファイル自体も含まなければなりません)。 暗黙的に統合機能を有効化します。

  • getLocalPath(): どのローカルパスの Dojo を使用しているかを取得します。

  • useLocalPath(): 統合機能がローカルパスの Dojo を使用しているかどうかを調べます。

  • setDjConfig(array $config): dojo または dijit の設定項目を設定します (連想配列で指定します)。

  • setDjConfigOption($option, $value): 単一の dojo または dijit 設定項目を設定します。

  • getDjConfig(): すべての dojo または dijit 設定値を取得します。

  • getDjConfigOption($option, $default = null): 単一の dojo または dijit 設定値を取得します。

  • addStylesheetModule($module): モジュールのテーマに基づいたスタイルシートを追加します。

  • getStylesheetModules(): モジュールのテーマとして登録されたスタイルシートを取得します。

  • addStylesheet($path): Dojo で使用するローカルスタイルシートを追加します。

  • getStylesheets(): ローカル Dojo スタイルシートを取得します。

  • addOnLoad($spec, $function = null): dojo.onLoad がコールするラムダ関数を追加します。 引数をひとつわたした場合は、 関数名あるいは javascript のクロージャと見なされます。 引数をふたつわたした場合は、 最初の引数がオブジェクトのインスタンスを表す変数名、 二番目の引数がそのオブジェクトのメソッド名あるいは そのオブジェクトで使用するクロージャと見なされます。

  • prependOnLoad($spec, $function = null): addOnLoad() と同じですが、onLoad スタックの先頭に追加するという点だけが異なります。

  • getOnLoadActions(): コンテナに登録されているすべての dojo.onLoad() アクションを取得します。 これは配列の配列となります。

  • onLoadCaptureStart($obj = null): dojo.onLoad() のラムダ関数として使用するデータをキャプチャします。 $obj が指定された場合は、キャプチャされた JS コードはその Javascript オブジェクトで使用するクロージャであると見なします。

  • onLoadCaptureEnd($obj = null): dojo.onLoad() で使用するデータのキャプチャを終了します。

  • javascriptCaptureStart(): 任意の javascript をキャプチャし、Dojo JS (onLoad や require など) として取り込めるようにします。

  • javascriptCaptureEnd(): javascript のキャプチャを終了します。

  • __toString(): コンテナを文字列にキャストします。すべての HTML style 要素および script 要素をレンダリングします。

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.

例354 Registering the Dojo View Helper Prefix Path

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

    <?php echo $view->accordionContainer(
        'foo',
        $content,
        array(
            'duration' => 200,
        ),
        array(
            'style' => 'width: 200px; height: 300px;',
        ),
    ); ?>
    
  • AccordionPane: dijit.layout.AccordionPane. For use within AccordionContainer.

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

    <?php echo $view->borderContainer(
        'foo',
        $content,
        array(
            'design' => 'headline',
        ),
        array(
            'style' => 'width: 100%; height: 100%',
        ),
    ); ?>
    
  • ContentPane: dijit.layout.ContentPane. Use inside any container except AccordionContainer.

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

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

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

    <?php echo $view->tabContainer(
        'foo',
        $content,
        array(),
        array(
            'style' => 'width: 400px; height: 500px; border: 1px;',
        ),
    ); ?>
    

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.

例355 BorderContainer layout dijit example

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

$view->borderContainer()->captureStart('masterLayout',
                                       array('design' => 'headline'));

echo $view->contentPane(
    'menuPane',
    'This is the menu pane',
    array('region' => 'top'),
    array('style' => 'background-color: darkblue;')
);

echo  $view->contentPane(
    'navPane',
    'This is the navigation pane',
    array('region' => 'left'),
    array('style' => 'width: 200px; background-color: lightblue;')
);

echo $view->contentPane(
    'mainPane',
    'This is the main content pane area',
    array('region' => 'center'),
    array('style' => 'background-color: white;')
);

echo $view->contentPane(
    'statusPane',
    'Status area',
    array('region' => 'bottom'),
    array('style' => 'background-color: lightgray;')
);

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.

    <?php echo $view->button(
        'foo',
        'Show Me!',
        array('iconClass' => 'myButtons'),
    ); ?>
    
  • 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.

    <?php echo $view->checkBox(
        'foo',
        'bar',
        array(),
        array(),
        array('checkedValue' => 'foo', 'unCheckedValue' => 'bar')
    ); ?>
    
  • 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.

    // As a select element:
    echo $view->comboBox(
        'foo',
        'bar',
        array(
            'autocomplete' => false,
        ),
        array(),
        array(
            'foo' => 'Foo',
            'bar' => 'Bar',
            'baz' => 'Baz',
        )
    );
    
    // As a dojo.data-enabled element:
    echo $view->comboBox(
        'foo',
        'bar',
        array(
            'autocomplete' => false,
            'store'        => 'stateStore',
            'storeType'    => 'dojo.data.ItemFileReadStore',
            'storeParams'  => array('url' => '/js/states.json'),
        ),
    );
    
  • 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.

    echo $view->currencyTextBox(
        'foo',
        '$25.00',
        array('currency' => 'USD'),
        array('maxlength' => 20)
    );
    

    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:

    $view->headMeta()->appendHttpEquiv('Content-Type',
                                       '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.

    echo $view->dateTextBox(
        'foo',
        '2008-07-11',
        array('required' => true)
    );
    
  • 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.

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

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

    echo $view->horizontalSlider(
        'foo',
        1,
        array(
            'minimum'             => -10,
            'maximum'             => 10,
            'discreteValues'      => 11,
            'intermediateChanges' => true,
            'showButtons'         => true,
            'topDecoration'       => array(
                'container' => 'topContainer'
                'dijit'     => 'HorizontalRuleLabels',
                'labels'    => array(
                    ' ',
                    '20%',
                    '40%',
                    '60%',
                    '80%',
                    ' ',
                ),
                'params' => array(
                    'container' => array(
                        'style' => 'height:1.2em; font-size=75%;color:gray;',
                    ),
                    'labels' => array(
                        'style' => 'height:1em; font-size=75%;color:gray;',
                    ),
                ),
            ),
            'bottomDecoration'    => array(
                'container' => 'bottomContainer'
                'labels'    => array(
                    '0%',
                    '50%',
                    '100%',
                ),
                'params' => array(
                    'container' => array(
                        'style' => 'height:1.2em; font-size=75%;color:gray;',
                    ),
                    'labels' => array(
                        'style' => 'height:1em; font-size=75%;color:gray;',
                    ),
                ),
            ),
        )
    );
    
  • 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.

    echo $view->numberSpinner(
        'foo',
        5,
        array(
            'min'    => -10,
            'max'    => 10,
            'places' => 2,
        ),
        array(
            'maxlenth' => 3,
        )
    );
    
  • 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.

    echo $view->numberTextBox(
        'foo',
        5,
        array(
            'places' => 4,
            'type'   => 'percent',
        ),
        array(
            'maxlength' => 20,
        )
    );
    
  • 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.

    echo $view->passwordTextBox(
        'foo',
        '',
        array(
            'required' => true,
        ),
        array(
            'maxlength' => 20,
        )
    );
    
  • 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.

    echo $view->radioButton(
        'foo',
        'bar',
        array(),
        array(),
        array(
            'foo' => 'Foo',
            'bar' => 'Bar',
            'baz' => 'Baz',
        )
    );
    
  • 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.

    echo $view->simpleTextarea(
        'foo',
        'Start writing here...',
        array(),
        array('style' => 'width: 90%; height: 5ems;')
    );
    
  • 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.

    echo $view->textarea(
        'foo',
        'Start writing here...',
        array(),
        array('style' => 'width: 300px;')
    );
    
  • 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'.

    echo $view->textBox(
        'foo',
        'some text',
        array(
            'trim'       => true,
            'propercase' => true,
            'maxLength'  => 20,
        ),
        array(
            'size' => 20,
        )
    );
    
  • 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.

    echo $view->timeTextBox(
        'foo',
        '',
        array(
            'am.pm'            => true,
            'visibleIncrement' => 'T00:05:00', // 5-minute increments
            'visibleRange'     => 'T02:00:00', // show 2 hours of increments
        ),
        array(
            'size' => 20,
        )
    );
    
  • 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.

    echo $view->validationTextBox(
        'foo',
        '',
        array(
            'required' => true,
            'regExp'   => '[\w]+',
            'invalidMessage' => 'No spaces or non-word characters allowed',
            'promptMessage'  => 'Single word consisting of alphanumeric ' .
                                'characters and underscores only',
        ),
        array(
            'maxlength' => 20,
        )
    );
    

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.

例356 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:

<?php echo $this->customDijit(
    'foo',
    $content,
    array(
        'dojoType' => 'dojox.layout.ContentPane',
        'title'    => 'Custom pane',
        'region'   => 'center'
    )
); ?>

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

<?php $this->customDijit()->captureStart(
    'foo',
    array(
        'dojoType' => 'dojox.layout.ContentPane',
        'title'    => 'Custom pane',
        'region'   => 'center'
    )
); ?>
This is the content of the pane
<?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:

class My_View_Helper_FooContentPane
    extends Zend_Dojo_View_Helper_CustomDijit
{
    protected $_defaultDojoType = 'foo.ContentPane';

    public function fooContentPane(
        $id = null, $value = null,
        array $params = array(), array $attribs = array()
    ) {
        return $this->customDijit($id, $value, $params, $attribs);
    }
}

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