Chapter 2. ZendX_JQuery

<sect1> <title>Introduction</title> <para> As of version 1.7, Zend Framework integrates <ulink>jQuery</ulink> view and form helpers through its extras library. The jQuery support is meant as an alternative to the already existing Dojo library integration. Currently jQuery can be integrated into your Zend Framework applications in the following ways: </para> <itemizedlist> <listitem><para>View helper to help setup the jQuery (Core and UI) environment</para></listitem> <listitem><para>jQuery UI specific Zend_View helpers</para></listitem> <listitem><para>jQuery UI specific Zend_Form elements and decorators</para></listitem> </itemizedlist> <para> By default the jQuery javascript dependencies are loaded from the Google Ajax Library Content Distribution Network. The CDN offers both jQuery Core and jQuery UI access points and the view helpers therefore can already offer you most the dependencies out of the box. Currently the Google CDN offers jQuery UI support up to version 1.5.2, but the jQuery view and form helpers already make use of the UI library 1.6 version (AutoComplete, ColorPicker, Spinner, Slider). To make use of these great additions you have to download the release candidate version of the <ulink>jQuery UI library</ulink> from its website. </para> </sect1><sect1> <title>ZendX_JQuery View Helpers</title> <para> Zend Framework provides jQuery related View Helpers through its Extras Library. These can be enabled in two ways, adding jQuery to the view helper path: </para> <programlisting> $view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper"); </programlisting> <para>Or using the <methodname>ZendX_JQuery::enableView(Zend_View_Interface $view)</methodname> method that does the same for you.</para> <sect2> <title>jQuery() View Helper</title> <para> The <methodname>jQuery()</methodname> view helper simplifies setup of your jQuery environment in your application. It takes care of loading the core and ui library dependencies if necessary and acts as a stack for all the registered onLoad javascript statements. All jQuery view helpers put their javascript code onto this stack. It acts as a collector for everything jQuery in your application with the following responsibilities: </para> <itemizedlist> <listitem><para>Handling deployment of CDN or a local path jQuery Core and UI libraries.</para></listitem> <listitem><para>Handling <ulink>$(document).ready()</ulink> events.</para></listitem> <listitem><para>Specifying additional stylesheet themes to use.</para></listitem> </itemizedlist> <para> The <methodname>jQuery()</methodname> view helper implementation, like its <methodname>dojo()</methodname> pendant, follows the placeholder architecture implementation; the data set in it persists between view objects, and may be directly echo'd from your layout script. Since views specified in a Zend_Layout script file are rendered before the layout itself, the <methodname>jQuery()</methodname> helper can act as a stack for jQuery statements and render them into the head segment of the html page. </para> <para>Contrary to Dojo, themes cannot be loaded from a CDN for the jQuery UI widgets and have to be implemented in your pages stylesheet file or loaded from an extra stylesheet file. A default theme called Flora can be obtained from the jQuery UI downloadable file.</para> <example> <title>jQuery() View Helper Example</title> <para> In this example a jQuery environment using the core and UI libraries will be needed. UI Widgets should be rendered with the Flora thema that is installed in 'public/styles/flora.all.css'. The jQuery libraries are both loaded from local paths. </para> <para> To register the jQuery functionality inside the view object, you have to add the appropriate helpers to the view helper path. There are many ways of accomplishing this, based on the requirements that the jQuery helpers have. If you need them in one specific view only, you can use the addHelperPath method on initialization of this view, or right before rendering: </para> <programlisting> $view->addHelperPath('ZendX/JQuery/View/Helper/', 'ZendX_JQuery_View_Helper'); </programlisting> <para>If you need them throughout your application, you can register them in your bootstrap file using access to the Controller Plugin ViewRenderer: </para> <programlisting> $view = new Zend_View(); $view->addHelperPath('ZendX/JQuery/View/Helper/', 'ZendX_JQuery_View_Helper'); $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer(); $viewRenderer->setView($view); Zend_Controller_Action_HelperBroker::addHelper($viewRenderer); </programlisting> <para>Now in the view script we want to display a Date Picker and an Ajax based Link.</para> <programlisting> <?php echo $this->ajaxLink("Show me something", "/hello/world", array('update' => '#content'));?> <div id="content"></div> <form method="post" action="/hello/world"> Pick your Date: <?php echo $this->datePicker("dp1", '', array( 'defaultDate' => date('Y/m/d', time())));?> <input type="submit" value="Submit" /> </form> </programlisting> <para>Both helpers now stacked some javascript statements on the jQuery helper and printed a link and a form element respectively. To access the javascript we have to utilize the jQuery() functionality. Both helpers already activated their dependencies that is they have called <methodname>jQuery()->enable()</methodname> and <methodname>jQuery()->uiEnable()</methodname>. We only have to print the jQuery() environment, and we choose to do so in the layout script's head segment: </para> <programlisting> <html> <head> <title>A jQuery View Helper Example</title> <?php echo $this->jQuery(); ?> </head> <body> <?php echo $this->layout()->content; ?> </body> </html> </programlisting> <para>Although <code>$this->layout()->content;</code> is printed behind the <code>$this->jQuery()</code> statement, the content of the view script is rendered before. This way all the javascript onLoad code has already been put on the onLoad stack and can be printed within the head segment of the html document. </para> </example> <sect3> <title>jQuery NoConflict Mode</title> <para>jQuery offers a noConflict mode that allows the library to be run side by side with other javascript libraries that operate in the global namespace, Prototype for example. The Zend Framework jQuery View Helper makes usage of the noConflict mode very easy. If you want to run Prototype and jQuery side by side you can call <code>ZendX_JQuery_View_Helper_JQuery::enableNoConflictMode();</code> and all jQuery helpers will operate in the No Conflict Mode.</para> <example> <title>Building your own Helper with No Conflict Mode</title> <para>To make use of the NoConflict Mode in your own jQuery helper, you only have to use the static method <methodname>ZendX_JQuery_View_Helper_JQuery::getJQueryHandler()</methodname> method. It returns the variable jQuery is operating in at the moment, either <code>$</code> or <varname>$j</varname> </para> <programlisting> class MyHelper_SomeHelper extends Zend_View_Helper_Abstract { public function someHelper() { $jquery = $this->view->jQuery(); $jquery->enable(); // enable jQuery Core Library // get current jQuery handler based on noConflict settings $jqHandler = ZendX_JQuery_View_Helper_JQuery::getJQueryHandler(); $function = '("#element").click(function() ' . '{ alert("noConflict Mode Save Helper!"); }' . ')'; $jquery->addOnload($jqHandler . $function); return ''; } } </programlisting> </example> </sect3> <sect3> <title>jQuery UI Themes</title> <para>Since there are no online available themes to use out of the box, the implementation of the UI library themes is a bit more complex than with the Dojo helper. The jQuery UI documentation describes for each component what stylesheet information is needed and the Default and Flora Themes from the downloadable archive give hints on the usage of stylesheets. The jQuery helper offers the function <code>jQuery()->addStylesheet($path);</code> function to include the dependant stylesheets whenever the helper is enabled and rendered. You can optionally merge the required stylesheet information in your main stylesheet file. </para> </sect3> <sect3> <title>Methods Available</title> <para> The <methodname>jQuery()</methodname> view helper always returns an instance of the jQuery placeholder container. That container object has the following methods available: </para> <sect4> <title>jQuery Core Library methods</title> <itemizedlist> <listitem><para><methodname>enable()</methodname>: explicitly enable jQuery integration.</para></listitem> <listitem><para><methodname>disable()</methodname>: disable jQuery integration.</para></listitem> <listitem><para><methodname>isEnabled()</methodname>: determine whether or not jQuery integration is enabled.</para></listitem> <listitem><para><methodname>setVersion()</methodname>: set the jQuery version that is used. This also decides on the library loaded from the Google Ajax Library CDN</para></listitem> <listitem><para><methodname>getVersion()</methodname>: get the current jQuery that is used. This also decides on the library loaded from the Google Ajax Library CDN</para></listitem> <listitem><para><methodname>useCdn()</methodname>: Return true, if CDN usage is currently enabled</para></listitem> <listitem><para><methodname>useLocalPath()</methodname>: Return true, if local usage is currently enabled</para></listitem> <listitem><para><methodname>setLocalPath()</methodname>: Set the local path to the jQuery Core library</para></listitem> <listitem><para><methodname>getLocalPath()</methodname>: If set, return the local path to the jQuery Core library</para></listitem> </itemizedlist> </sect4> <sect4> <title>jQuery UI Library methods</title> <itemizedlist> <listitem><para><methodname>uiEnable()</methodname>: explicitly enable jQuery UI integration.</para></listitem> <listitem><para><methodname>uiDisable()</methodname>: disable jQuery UI integration.</para></listitem> <listitem><para><methodname>uiIsEnabled()</methodname>: determine whether or not jQuery UI integration is enabled.</para></listitem> <listitem><para><methodname>setUiVersion()</methodname>: set the jQuery UI version that is used. This also decides on the library loaded from the Google Ajax Library CDN</para></listitem> <listitem><para><methodname>getUiVersion()</methodname>: get the current jQuery UI that is used. This also decides on the library loaded from the Google Ajax Library CDN</para></listitem> <listitem><para><methodname>useUiCdn()</methodname>: Return true, if CDN usage is currently enabled for jQuery UI</para></listitem> <listitem><para><methodname>useUiLocal()</methodname>: Return true, if local usage is currently enabled for jQuery UI</para></listitem> <listitem><para><methodname>setUiLocalPath()</methodname>: Set the local path to the jQuery UI library</para></listitem> <listitem><para><methodname>getUiLocalPath()</methodname>: If set, get the local path to the jQuery UI library</para></listitem> </itemizedlist> </sect4> <sect4> <title>jQuery Helper Utility methods</title> <itemizedlist> <listitem><para><methodname>setView(Zend_View_Interface $view)</methodname>: set a view instance in the container.</para></listitem> <listitem><para><methodname>onLoadCaptureStart()</methodname>: Start capturing javascript code for jQuery onLoad execution.</para></listitem> <listitem><para><methodname>onLoadCaptureEnd()</methodname>: Stop capturing</para></listitem> <listitem><para><methodname>javascriptCaptureStart()</methodname>: Start capturing javascript code that has to be rendered after the inclusion of either jQuery Core or UI libraries.</para></listitem> <listitem><para><methodname>javascriptCaptureEnd()</methodname>: Stop capturing.</para></listitem> <listitem><para><methodname>addJavascriptFile($path)</methodname>: Add javascript file to be included after jQuery Core or UI library.</para></listitem> <listitem><para><methodname>getJavascriptFiles()</methodname>: Return all currently registered additional javascript files.</para></listitem> <listitem><para><methodname>clearJavascriptFiles()</methodname>: Clear the javascript files</para></listitem> <listitem><para><methodname>addJavascript($statement)</methodname>: Add javascript statement to be included after jQuery Core or UI library.</para></listitem> <listitem><para><methodname>getJavascript()</methodname>: Return all currently registered additional javascript statements.</para></listitem> <listitem><para><methodname>clearJavascript()</methodname>: Clear the javascript statements.</para></listitem> <listitem><para><methodname>addStylesheet($path)</methodname>: Add a stylesheet file that is needed for a jQuery view helper to display correctly.</para></listitem> <listitem><para><methodname>getStylesheets()</methodname>: Get all currently registered additional stylesheets.</para></listitem> <listitem><para><methodname>addOnLoad($statement)</methodname>: Add javascript statement that should be executed on document loading.</para></listitem> <listitem><para><methodname>getOnLoadActions()</methodname>: Return all currently registered onLoad statements.</para></listitem> <listitem><para><methodname>setRenderMode($mask)</methodname>: Render only a specific subset of the jQuery environment via ZendX_JQuery::RENDER_ constants. Rendering all elements is the default behaviour.</para></listitem> <listitem><para><methodname>getRenderMode()</methodname>: Return the current jQuery environment rendering mode.</para></listitem> <listitem><para><methodname>setCdnSsl($bool)</methodname>: Set if the CDN Google Ajax Library should be loaded from an SSL or a Non-SSL location.</para></listitem> </itemizedlist> <para>These are quite a number of methods, but many of them are used for internally by all the additional view helpers and during the printing of the jQuery environment. Unless you want to build your own jQuery helper or have a complex use-case, you will probably only get in contact with a few methods of these.</para> </sect4> </sect3> <sect3> <title>Refactoring jQuery environment with setRenderMode()</title> <para>Using the current setup that was described, each page of your website would show a different subset of jQuery code that would be needed to keep the current jQuery related items running. Also different files or stylesheets may be included depending on which helpers you implemented in your application. In production stage you might want to centralize all the javascript your application generated into a single file, or disable stylesheet rendering because you have merged all the stylesheets into a single file and include it statically in your layout. To allow a smooth refactoring you can enable or disable the rendering of certain jQuery environment blocks with help of the following constants and the <methodname>jQuery()->setRenderMode($bitmask)</methodname> function.</para> <itemizedlist> <listitem><para><code>ZendX_JQuery::RENDER_LIBRARY</code>: Renders jQuery Core and UI library</para></listitem> <listitem><para><code>ZendX_JQuery::RENDER_SOURCES</code>: Renders additional javascript files</para></listitem> <listitem><para><code>ZendX_JQuery::RENDER_STYLESHEETS</code>: Renders jQuery related stylesheets</para></listitem> <listitem><para><code>ZendX_JQuery::RENDER_JAVASCRIPT</code>: Render additional javascript statements</para></listitem> <listitem><para><code>ZendX_JQuery::RENDER_JQUERY_ON_LOAD</code>: Render jQuery onLoad statements</para></listitem> <listitem><para><code>ZendX_JQuery::RENDER_ALL</code>: Render all previously mentioned blocks, this is default behaviour.</para></listitem> </itemizedlist> <para> For an example, if you would have merged jQuery Core and UI libraries as well as other files into a single large file as well as merged stylesheets to keep HTTP requests low on your production application. You could disallow the jQuery helper to render those parts, but render all the other stuff with the following statement in your view: </para> <programlisting> $view->jQuery() ->setRenderMode(ZendX_JQuery::RENDER_JAVASCRIPT | ZendX_JQuery::RENDER_JQUERY_ON_LOAD); </programlisting> <para>This statement makes sure only the required javascript statements and onLoad blocks of the current page are rendered by the jQuery helper.</para> </sect3> <sect3> <title>Migrations</title> <para>Prior to 1.8 the methods <methodname>setCdnVersion()</methodname>, <methodname>setLocalPath()</methodname> <methodname>setUiCdnVersion()</methodname> and <methodname>setUiLocalPath()</methodname> all enabled the view helper upon calling, which is considered a bug from the following perspective: If you want to use the any non-default library option, you would have to manually disable the jQuery helper aftwards if you only require it to be loaded in some scenarios. With version 1.8 the jQuery helper does only enable itsself, when <methodname>enable()</methodname> is called, which all internal jQuery View helpers do upon being called. </para> </sect3> </sect2> <sect2> <title>JQuery Helpers</title> <sect3> <title>AjaxLink Helper</title> <para>The AjaxLink helper uses jQuery's ajax capabilities to offer the creation of links that do ajax requests and inject the response into a chosen DOM element. It also offers the possibility to append simple jQuery effects to both the link and the response DOM element. A simple example introduces its functionality:</para> <programlisting> <!-- Inside your View Object --> <div id="container"></div> <?php echo $this->view->ajaxLink("Link Name", "url.php", array('update' => '#container')); ?> </programlisting> <para>This example creates a link with the label "Link Name" that fires an ajax request to url.php upon click and renders the response into the div container "#container". The function header for the ajaxLink is as follows: <code>function ajaxLink($label, $url, $options, $params);</code> The options array is very powerful and offers you lots of functionality to customize your ajax requests.</para> <para>Available options are:</para> <table> <title>AjaxLink options</title> <tgroup> <thead> <row> <entry>Option</entry> <entry>Data Type</entry> <entry>Default Value</entry> <entry>Description</entry> </row> </thead> <tbody> <row> <entry><code>update</code></entry> <entry><code>string</code></entry> <entry><code>false</code></entry> <entry> Container to inject response content into, use jQuery CSS Selector syntax, ie. "#container" or ".box" </entry> </row> <row> <entry><code>method</code></entry> <entry><code>string</code></entry> <entry><code>Implicit GET or POST</code></entry> <entry>Request method, is implicitly chosen as GET when no parameters given and POST when parameters given.</entry> </row> <row> <entry><code>complete</code></entry> <entry><code>string</code></entry> <entry><code>false</code></entry> <entry>Javascript callback executed, when ajax request is complete. This option allows for shortcut effects, see next section.</entry> </row> <row> <entry><code>beforeSend</code></entry> <entry><code>string</code></entry> <entry><code>false</code></entry> <entry>Javascript callback executed right before ajax request is started. This option allows for shortcut effects, see next section.</entry> </row> <row> <entry><code>noscript</code></entry> <entry><code>boolean</code></entry> <entry><code>true</code></entry> <entry>If true the link generated will contain a href attribute to the given link for non-javascript enabled browsers. If false href will resolve to "#".</entry> </row> <row> <entry><code>dataType</code></entry> <entry><code>string</code></entry> <entry><code>html</code></entry> <entry>What type of data is the Ajax Response of? Possible are Html, Text, Json. Processing Json responses has to be done with custom "complete" callback functions.</entry> </row> <row> <entry><code>attribs</code></entry> <entry><code>array</code></entry> <entry><code>null</code></entry> <entry>Additional HTML attributes the ajaxable link should have.</entry> </row> <row> <entry><code>title, id, class</code></entry> <entry><code>string</code></entry> <entry><code>false</code></entry> <entry>Convenience shortcuts for HTML Attributes.</entry> </row> <row> <entry><code>inline</code></entry> <entry><code>boolean</code></entry> <entry><code>false</code></entry> <entry>Although far from best practice, you can set javascript for this link inline in "onclick" attribute.</entry> </row> </tbody> </tgroup> </table> <para>To enlighten the usage of this helper it is best to show another bunch of more complex examples. This example assumes that you have only one view object that you want to display and don't care a lot about html best practices, since we have to output the jQuery environment just before the closing body tag.</para> <programlisting> <html> <head> <title>Zend Framework jQuery AjaxLink Example</title> <script language="javascript" type="text/javascript" src="myCallbackFuncs.js"></script> </head> <body> <!-- without echoing jQuery this following --> <!-- list only prints a list of for links --> <ul> <li> <?php echo $this->ajaxLink("Example 1", "/ctrl/action1", array('update' => '#content', 'noscript' => false, 'method' => 'POST')); ?> </li> <li> <?php echo $this->ajaxLink("Example 2", "/ctrl/action2", array('update' => '#content', 'class' => 'someLink'), array('param1' => 'value1', 'param2' => 'value2')); ?> </li> <li><?php echo $this->ajaxLink("Example 3", "/ctrl/action3", array('dataType' => 'json', 'complete' => 'alert(data)')); ?> </li> <li><?php echo $this->ajaxLink("Example 4", "/ctrl/action4", array('beforeSend' => 'hide', 'complete' => 'show')); ?> </li> <li> <?php echo $this->ajaxLink("Example 5", "/ctrl/action5", array( 'beforeSend' => 'myBeforeSendCallbackJsFunc();', 'complete' => 'myCompleteCallbackJsFunc(data);') ); ?> </li> </ul> <!-- only at this point the javascript is printed to sreen --> <?php echo $this->jQuery(); ?> </body> </html> </programlisting> <para>You might have already seen that the 'update', 'complete', and 'beforeSend' options have to be executed in specific order and syntax so that you cannot use those callbacks and override their behaviour completely when you are using <methodname>ajaxLink()</methodname>. For larger use cases you will probably want to write the request via jQuery on your own. The primary use case for the callbacks is effect usage, other uses may very well become hard to maintain. As shown in Example Link 5, you can also forward the beforeSend/complete Callbacks to your own javascript functions.</para> <sect4> <title>Shortcut Effects</title> <para>You can use shortcut effect names to make your links actions more fancy. For example the Container that will contain the ajax response may very well be invisible in the first place. Additionally you can use shortcut effects on the link to hide it after clicking. The following effects can be used for callbacks:</para> <itemizedlist> <listitem><para><code>complete</code> callback: 'show', 'showslow', 'shownormal', 'showfast', 'fadein', 'fadeinslow', 'fadeinfast', 'slidedown', 'slidedownslow', 'slidedownfast'. These all correspond to the jQuery effects fadeIn(), show() and slideDown() and will be executed on the container specified in <code>update</code>.</para></listitem> <listitem><para><code>beforeSend</code> callback: 'fadeout', 'fadeoutslow', 'fadeoutfast', 'hide', 'hideslow', 'hidefast', 'slideup'. These correspond to the jQuery effects fadeOut(), hide(), slideUp() and are executed on the clicked link.</para></listitem> </itemizedlist> <programlisting> <?php echo $this->ajaxLink("Example 6", "/ctrl/action6", array('beforeSend' => 'hide', 'complete' => 'show')); ?> </programlisting> </sect4> </sect3> <sect3> <title>jQuery UI Library Helpers</title> <para>The jQuery UI Library offers a range of layout and form specific widgets that are integrated into the Zend Framework via View Helpers. The form-elements are easy to handle and will be described first, whereas the layout specific widgets are a bit more complex to use.</para> <sect4> <title>jQuery UI Form Helpers</title> <para>The method signature for all form view helpers closely resembles the Dojo View helpers signature, <methodname>helper($id, $value, $params, $attribs)</methodname>. A description of the parameters follows:</para> <itemizedlist> <listitem><para><varname>$id</varname>: Will act as the identifier name for the helper element inside a form. If in the attributes no id element is given, this will also become the form element id, that has to be unique across the DOM.</para></listitem> <listitem><para><varname>$value</varname>: Default value of the element.</para></listitem> <listitem><para><varname>$params</varname>: Widget specific parameters that customize the look and feel of the widget. These options are unique to each widget and <ulink> described in the jQuery UI documentation</ulink>. The data is casted to JSON, so make sure to use the <classname>Zend_Json_Expr</classname> class to mark executable javascript as safe.</para></listitem> <listitem><para><varname>$attribs</varname>: HTML Attributes of the Form Helper</para></listitem> </itemizedlist> <para>The following UI widgets are available as form view helpers. Make sure you use the correct version of jQuery UI library to be able to use them. The Google CDN always offers you the latest released version.</para> <itemizedlist> <listitem><para><methodname>autoComplete($id, $value, $params, $attribs)</methodname>: The AutoComplete View helper is part of jQuery UI since version 1.8 and creates a text field and registeres it to have auto complete functionality. The completion data source has to be given as jQuery related parameters 'url' or 'data' as described in the jQuery UI manual. </para></listitem> <listitem><para><methodname>colorPicker($id, $value, $params, $attribs)</methodname>: ColorPicker is still a ZendX_JQuery element for legacy reason, but was removed from jQuery UI completly. </para></listitem> <listitem><para><methodname>datePicker($id, $value, $params, $attribs)</methodname>: Create a DatePicker inside a text field. This widget is available since jQuery UI 1.5 and can therefore currently be used with the Google CDN. Using the 'handles' option to create multiple handles overwrites the default set value and the jQuery parameter 'startValue' internally inside the view helper.</para></listitem> <listitem><para><methodname>slider($id, $value, $params, $attribs)</methodname>: Create a Sliding element that updates its value into a hidden form field. Available since jQuery UI 1.5.</para></listitem> <listitem><para><methodname>spinner($id, $value, $params, $attribs)</methodname>: Create a Spinner element that can spin through numeric values in a specified range. This element was removed from the 1.6 jQuery UI release and has not been re-released yet.</para></listitem> </itemizedlist> <example> <title>Showing jQuery Form View Helper Usage</title> <para>In this example we want to simulate a fictional web application that offers auctions on travel locations. A user may specify a city to travel, a start and end date, and a maximum amount of money he is willing to pay. Therefore we need an autoComplete field for all the currently known travel locations, a date picker for start and end dates and a spinner to specify the amount.</para> <programlisting> <form method="post" action="bid.php"> <label for="locaction">Where do you want to travel?</label> <?php echo $this->autoComplete("location", "", array('source' => array('New York', 'Mexico City', 'Sydney', 'Ruegen', 'Baden Baden'))); ?> <br /> <label for="startDate">Travel Start Date:</label> <?php echo $this->datePicker("startDate", '', array( 'defaultDate' => '+7', 'minDate' => '+7', 'onClose' => new Zend_Json_Expr('myJsonFuncCechkingValidity'))); ?> <br /> <label for="startDate">Travel End Date:</label> <?php echo $this->datePicker("endDate", '', array( 'defaultDate' => '+14', 'minDate' => '+7', 'onClose' => new Zend_Json_Expr('myJsonFuncCechkingValidity'))); ?> <br /> <label for="bid">Your Bid:</label> <?php echo $this->spinner("bid", "", array('min' => 1205.50, 'max' => 10000, 'start' => 1205.50, 'currency' => '€')); ?> <br /> <input type="submit" value="Bid!" /> </form> </programlisting> <para>You can see the use of jQuery UI Widget specific parameters. These all correspond to those given in the jQuery UI docs and are converted to JSON and handed through to the view script.</para> </example> </sect4> <sect4> <title>Using an Action Helper to Send Data to AutoComplete</title> <para>The jQuery UI Autocomplete Widget can load data from a remote location rather than from an javascript array, making its usage really useful. Zend Framework currently providers a bunch of server-side AutoComplete Helpers and there is one for jQuery too. You register the helper to the controller helper broker and it takes care of disabling layouts and renders an array of data correctly to be read by the AutoComplete field. To use the Action Helper you have to put this rather long statement into your bootstrap or Controller initialization function: </para> <programlisting> Zend_Controller_Action_HelperBroker::addHelper( new ZendX_JQuery_Controller_Action_Helper_AutoComplete() ); </programlisting> <para>You can then directly call the helper to render AutoComplete Output in your Controller</para> <programlisting> class MyIndexController extends Zend_Controller_Action { public function autocompleteAction() { // The data sent via the ajax call is inside $_GET['q'] $filter = $_GET['q']; // Disable Layout and stuff, just displaying AutoComplete Information. $this->_helper->autoComplete(array("New York", "Bonn", "Tokio")); } } </programlisting> </sect4> <sect4> <title>jQuery UI Layout Helpers</title> <para>There is a wide range of Layout helpers that the UI library offers. The ones covered by Zend Framework view helpers are Accordion, Dialog, Tabs. Dialog is the most simple one, whereas Accordion and Tab extend a common abstract class and offer a secondary view helper for pane generation. The following view helpers exist in the jQuery view helpers collection, an example accompanies them to show their usage.</para> <itemizedlist> <listitem><para><methodname>dialogContainer($id, $content, $params, $attribs)</methodname>: Create a Dialog Box that is rendered with the given content.on startup. If the option 'autoOpen' set to false is specified the box will not be displayed on load but can be shown with the additional <methodname>dialog("open")</methodname> javascript function. See UI docs for details.</para></listitem> <listitem><para><methodname>tabPane($id, $content, $options)</methodname>: Add a new pane to a tab container with the given <varname>$id</varname>. The given <varname>$content</varname> is shown in this tab pane. To set the title use <varname>$options['title']</varname>. If <varname>$options['contentUrl']</varname> is set, the content of the tab is requested via ajax on tab activation. </para></listitem> <listitem><para><methodname>tabContainer($id, $params, $attribs)</methodname>: Render a tab container with all the currently registered panes. This view helper also offers to add panes with the following syntax: <code>$this->tabContainer()->addPane($id, $label, $content, $options)</code>. </para></listitem> <listitem><para><methodname>accordionPane($id, $content, $options)</methodname>: Add a new pane to the accordion container with the given <varname>$id</varname>. The given <varname>$content</varname> is shown in this tab pane. To set the title use <varname>$options['title']</varname>. </para></listitem> <listitem><para><methodname>accordionContainer($id, $params, $attribs)</methodname>: Render an accordion container with all the currently registered panes. This view helper also offers to add panes with the following syntax: <code>$this->accordionContainer()->addPane($id, $label, $content, $options)</code>. </para></listitem> </itemizedlist> <example> <title>Showing the latest news in a Tab Container</title> <para>For this example we assume the developer already wrote the controller and model side of the script and assigned an array of news items to the view script. This array contains at most 5 news elements, so we don't have to care about the tab container getting to many tabs.</para> <programlisting> <?php foreach($this->news AS $article): ?> <?php $this->tabPane("newstab", $article->body, array('title' => $article->title)); ?> <?php endforeach; ?> <h2>Latest News</h2> <?php echo $this->tabContainer("newstab", array(), array('class' => 'flora')); ?> </programlisting> </example> </sect4> </sect3> </sect2> </sect1><sect1> <title>ZendX_JQuery Form Elements and Decorators</title> <para>All View Helpers are pressed into Zend_Form elements or decorators also. They can even be easily integrated into your already existing forms. To enable a Form for Zend_JQuery support you can use two ways: Init your form as <code>$form = new ZendX_JQuery_Form();</code> or use the static method <methodname>ZendX_JQuery::enableForm($form)</methodname> to enable jQuery element support. </para> <sect2> <title>General Elements and Decorator Usage</title> <para>Both elements and decorators of the Zend jQuery Form set can be initialized with the option key <code>jQueryParams</code> to set certain jQuery object related parameters. This jQueryParams array of options matches to the <varname>$params</varname> variable of the corresponding view helpers. For example:</para> <programlisting> $element = new ZendX_JQuery_Form_Element_DatePicker( 'dp1', array('jQueryParams' => array('defaultDate' => '2007/10/10')) ); // would internally call to: $view->datePicker("dp1", "", array('defaultDate' => '2007/10/10'), array()); </programlisting> <para>Additionally elements jQuery options can be customized by the following methods:</para> <itemizedlist> <listitem><para><methodname>setJQueryParam($name, $value)</methodname>: Set the jQuery option <varname>$name</varname> to the given value.</para></listitem> <listitem><para><methodname>setJQueryParams($params)</methodname>: Set key value pairs of jQuery options and merge them with the already set options.</para></listitem> <listitem><para><methodname>getJQueryParam($name)</methodname>: Return the jQuery option with the given name.</para></listitem> <listitem><para><methodname>getJQueryParams()</methodname>: Return an array of all currently set jQuery options.</para></listitem> </itemizedlist> <para>Each jQuery related Decorator also owns a <methodname>getJQueryParams()</methodname> method, to set options you have to use the <methodname>setDecorators()</methodname>, <methodname>addDecorator()</methodname> or <methodname>addDecorators()</methodname> functionality of a form element and set the jQueryParams key as option:</para> <programlisting> $form->setDecorators(array( 'FormElements', array('AccordionContainer', array( 'id' => 'tabContainer', 'style' => 'width: 600px;', 'jQueryParams' => array( 'alwaysOpen' => false, 'animated' => "easeslide" ), )), 'Form' )); </programlisting> </sect2> <sect2> <title>Form Elements</title> <para>The Zend Framework jQuery Extras Extension comes with the following Form Elements:</para> <itemizedlist> <listitem><para><code>ZendX_JQuery_Form_Element_AutoComplete</code>: Proxy to AutoComplete View Helper</para></listitem> <listitem><para><code>ZendX_JQuery_Form_Element_ColorPicker</code>: Proxy to ColorPicker View Helper</para></listitem> <listitem><para><code>ZendX_JQuery_Form_Element_DatePicker</code>: Proxy to DatePicker View Helper</para></listitem> <listitem><para><code>ZendX_JQuery_Form_Element_Slider</code>: Proxy to Slider View Helper</para></listitem> <listitem><para><code>ZendX_JQuery_Form_Element_Spinner</code>: Proxy to Spinner View Helper</para></listitem> </itemizedlist> <note> <title>jQuery Decorators: Beware the Marker Interface for UiWidgetElements</title> <para>By default all the jQuery Form elements use the <code>ZendX_JQuery_Form_Decorator_UiWidgetElement</code> decorator for rendering the jQuery element with its specific view helper. This decorator is inheritly different from the ViewHelper decorator that is used for most of the default form elements in Zend_Form. To ensure that rendering works correctly for jQuery form elements at least one decorator has to implement the <code>ZendX_JQuery_Form_Decorator_UiWidgetElementMarker</code> interface, which the default decorator does. If no marker interface is found an exception is thrown. Use the marker interface if you want to implement your own decorator for the jQuery form element specific rendering. </para> </note> </sect2> <sect2> <title>Form Decorators</title> <para>The following Decorators come with the Zend Framework jQuery Extension:</para> <itemizedlist> <listitem><para><code>ZendX_JQuery_Form_Decorator_AccordionContainer</code>: Proxy to AccordionContainer View Helper</para></listitem> <listitem><para><code>ZendX_JQuery_Form_Decorator_AccordionPane</code>: Proxy to AccordionPane View Helper</para></listitem> <listitem><para><code>ZendX_JQuery_Form_Decorator_DialogContainer</code>: Proxy to DialogContainer View Helper</para></listitem> <listitem><para><code>ZendX_JQuery_Form_Decorator_TabContainer</code>: Proxy to TabContainer View Helper</para></listitem> <listitem><para><code>ZendX_JQuery_Form_Decorator_TabPane</code>: Proxy to TabPane View Helper</para></listitem> <listitem><para><code>ZendX_JQuery_Form_Decorator_UiWidgetElement</code>: Decorator to Display jQuery Form Elements</para></listitem> </itemizedlist> <para>Utilizing the Container elements is a bit more complicated, the following example builds a Form with 2 SubForms in a TabContainer:</para> <example> <title>SubForms with TabContainer Decorator</title> <para>The following example makes use of all Form elements and wraps them into 2 subforms that are decorated with a tab container. First we build the basic <code>ZendX_JQuery_Form</code>:</para> <programlisting> $form = new ZendX_JQuery_Form(); $form->setAction('formdemo.php'); $form->setAttrib('id', 'mainForm'); $form->setAttrib('class', 'flora'); $form->setDecorators(array( 'FormElements', array('TabContainer', array( 'id' => 'tabContainer', 'style' => 'width: 600px;', )), 'Form', )); </programlisting> <para>Setting the Form Id (in this case to 'mainForm') is an important step for the TabContainer. It is needed that the subforms can relate to the Container Id in a later form building stage. We now initialize two SubForms that will be decorated with the <code>TabPane</code> decorators:</para> <programlisting> $subForm1 = new ZendX_JQuery_Form(); $subForm1->setDecorators(array( 'FormElements', array('HtmlTag', array('tag' => 'dl')), array('TabPane', array('jQueryParams' => array('containerId' => 'mainForm', 'title' => 'DatePicker and Slider'))) )); $subForm2 = new ZendX_JQuery_Form(); $subForm2->setDecorators(array( 'FormElements', array('HtmlTag', array('tag' => 'dl')), array('TabPane', array('jQueryParams' => array('containerId' => 'mainForm', 'title' => 'AutoComplete and Spinner'))) )); </programlisting> <para>In this stage it is important that the <code>'containerId'</code> option is set in each SubForm TabPane, or the subforms cannot relate back to the tab Container and would not be displayed. To enforce this setting, an exception of the type <code>ZendX_JQuery_Exception</code> is thrown if the option is not set. We can now add all the desired elements to the subforms:</para> <programlisting> // Add Element Date Picker $elem = new ZendX_JQuery_Form_Element_DatePicker( "datePicker1", array("label" => "Date Picker:") ); $elem->setJQueryParam('dateFormat', 'dd.mm.yy'); $subForm1->addElement($elem); // Add Element Spinner $elem = new ZendX_JQuery_Form_Element_Spinner( "spinner1", array('label' => 'Spinner:') ); $elem->setJQueryParams(array('min' => 0, 'max' => 1000, 'start' => 100)); $subForm1->addElement($elem); // Add Slider Element $elem = new ZendX_JQuery_Form_Element_Slider( "slider1", array('label' => 'Slider:') ); $elem->setJQueryParams(array('defaultValue' => '75')); $subForm2->addElement($elem); // Add Autocomplete Element $elem = new ZendX_JQuery_Form_Element_AutoComplete( "ac1", array('label' => 'Autocomplete:') ); $elem->setJQueryParams(array('source' => array('New York', 'Berlin', 'Bern', 'Boston'))); $subForm2->addElement($elem); // Submit Button $elem = new Zend_Form_Element_Submit("btn1", array('value' => 'Submit')); $subForm1->addElement($elem); </programlisting> <para>Three additional lines are missing to put it all together and we have a jQuery animated form:</para> <programlisting> $form->addSubForm($subForm1, 'subform1'); $form->addSubForm($subForm2, 'subform2'); $formString = $form->render($view); </programlisting> </example> <example> <title>Wrapping a Form into the Dialog Container</title> <para>The only use for the Dialog Container in Zend Form context is to wrap itself around a form and display it in a dialog. Its important to remember that the order of the decorators has to be different than in the Accordion and Tab Container examples.</para> <programlisting> // Create new jQuery Form $form = new ZendX_JQuery_Form(); $form->setAction('formdemo.php'); // Wrap the complete form inside a Dialog box $form->setDecorators(array( 'FormElements', 'Form', array('DialogContainer', array( 'id' => 'tabContainer', 'style' => 'width: 600px;', 'jQueryParams' => array( 'tabPosition' => 'top' ), )), )); // Add Element Spinner $elem = new ZendX_JQuery_Form_Element_Spinner("spinner1", array('label' => 'Spinner:', 'attribs' => array('class' => 'flora'))); $elem->setJQueryParams(array('min' => 0, 'max' => 1000, 'start' => 100)); $form->addElement($elem); </programlisting> </example> </sect2> </sect1>