The Name Of My Page"

From Documentation
m (correct highlight (via JWB))
 
(2 intermediate revisions by one other user not shown)
Line 1: Line 1:
 
{{Template:Smalltalk_Author|
 
{{Template:Smalltalk_Author|
|author=Matthieu Duchemin, Engineer, Potix Corporation
+
|author=Robert Wenzel, Engineer, Potix Corporation
|date=January 2016
+
|date=April 2016
 
|version=ZK 8.0
 
|version=ZK 8.0
 
}}
 
}}
  
ZK Framework offer lots of features to simplify the creation of a Java based web application. As some of these features are not always known, we sometime come across suboptimal implementation. Usually, it only take a few simple steps to make them simpler and easier. Those aren't necessarily broken or damaging, but they can have positive effects without much changes or efforts.
+
= Introduction =
You will find here a few common mistakes in ZK, and solutions to avoid them.
 
  
=ZK Do's and Don'ts Part 1=
+
*[[Small_Talks/2015/September/ZK8_Wizard_Example_-_Part_1|Part 1 - Defining the Wizard]]
 +
*[[Small_Talks/2015/September/ZK8_Wizard_Example_-_Part_2|Part 2 - Order Wizard (a more complex example)]]
 +
*[[Small_Talks/2016/February/ZK8_Wizard_Example_-_Part_3|Part 3 - Form Handling and Input Validation]]
 +
*[[Small_Talks/2016/March/ZK8_Wizard_Example_-_Part_4|Part 4 - Styling the Wizard (with Bootstrap)]] (You are here)
  
==Calling components directly when using a model==
+
To wrap up the Wizard Example Series, here is the final Part showing how things finally fit together when applying a 3rd party CSS framework (Bootstrap) to the wizard.
ZK offers default ListModel<ref>http://books.zkoss.org/wiki/ZK_Developer's_Reference/MVC/Model/List_Model</ref> implementations such as ListModelList. They provide an easy way to separate the view from the model. By providing a template or a renderer to control the appearance, and a model to handle the data.
 
While delegating control to the model, it feel sometime "easier" to act directly on a component. One would use grid.getRows().appendChild(..) to add a new row, or use listbox.setSelectedIndex() to set the selection state of a Listbox.
 
If the components content is directly controlled by the application, this may be correct. However, if the content is controlled by a model, the model itself should perform these actions.
 
<br/>
 
;Do:
 
*Use ListModels instead of basic collections when assigning a model to a component.
 
**List – ListModelList <ref>https://www.zkoss.org/javadoc/latest/zk/org/zkoss/zul/ListModelList.html</ref>
 
**Set – ListModelSet <ref>https://www.zkoss.org/javadoc/latest/zk/org/zkoss/zul/ListModelSet.html</ref>
 
**Map - ListModelMap <ref>https://www.zkoss.org/javadoc/latest/zk/org/zkoss/zul/ListModelMap.html</ref>
 
**Object[] or Enum – ListModelArray <ref>https://www.zkoss.org/javadoc/latest/zk/org/zkoss/zul/ListModelArray.html</ref>
 
*Use ListModel methods to apply changes to the model.
 
<br/>
 
;Don’t:
 
*Use component methods to alter the view when using a model.
 
*Mix model and manual entries in the same component.
 
  
==Understanding ZK scopes==
+
The implementation decisions/techniques used in the previous chapters now become handy. The strict separation between view and viewModel code enables the style overhaul [https://github.com/zkoss-demo/zk-wizard-example/commit/ba276f513ce7ee6c7f5428068deaa4a6ac6e38de without touching any Java code].
Scopes in ZK define the range affected by and action. For example, when creating an event queue, we need to define the scope of listeners affected by its events.
+
Restyling an application still requires a significant amount of work, in which the major task is to adjust the various zul pages and templates to render the markup required by Bootstrap. However, compared to changing both zul and java code, the possibility of introducing errors is much smaller (and even if new problems arise, they are obviously somewhere in the view).
The basic scopes are DESKTOP, SESSION and APPLICATION. <ref>http://books.zkoss.org/wiki/ZK_Developer's_Reference/Event_Handling/Event_Queues#More_About_Scopes</ref>
 
APPLICATION is very straightforward: it will affect every listeners on the whole application.
 
SESSION represent the browser session. Assuming that the client uses cookies, it will match each tab in the browser.
 
DESKTOP roughly represents a unique browser tab. In specific cases, like Iframe, a tab can contain more than one desktop.
 
When using events, choosing the right scope can lead to increased performances, reduced network activity and reduced memory consumption. It’s also work remembering that using an event queue with any scope except Desktop will automatically activate server push.
 
<br/>
 
;Do:
 
*Always use the smallest possible scope.
 
*Be careful when using session scope, as it will affect every desktops in the session.
 
*Be extra careful when using application scope, as it will affect any desktops in the application.
 
<br/>
 
;Don’t:
 
*Use a scope broader than desktop unless you are sure that you need it.
 
*Choose session or application if you do not want server push to be activated.
 
  
==Component belong to another desktop==
+
Here is a recording of the results (descriptions of the most significant changes will follow below):
Saving a reference to a component can be a powerful way to keep track of changes, but there is one pitfall to avoid. ZK components are bound to a desktop, and cannot be passed around to another desktop or session.
 
Choosing where to save or send the component reference is critical, as accessing it outside of its original desktop would cause exceptions in the best case, and corrupted views in the worst. To avoid this, always use desktop scope when passing around components, and only send values when serving a whole session or application.
 
<br/>
 
;Do:
 
*Keep references of business objects, values between desktops if needed.
 
*Use event queues for live data. Use session or application parameters for static data.
 
<br/>
 
;Don’t:
 
*Keep a reference to a view object such as a component as a session or application parameter.
 
*Send a reference to a view object in an event queue with a scope is broader than desktop.
 
  
==Choosing @init, @load, @save, or @bind==
+
<gflash width="910" height="657">Order-wizard_with_style.swf</gflash>
Using the MVVM data-binding annotations to wire a view model and a view, you may use these four annotations.
+
[[File:Order-wizard_with_style.swf]]
*@init will load the value in the view once, but will not update it.<ref>http://books.zkoss.org/zk-mvvm-book/8.0/syntax/databindinginit.html</ref>
 
*@load will load the value in the view, then updated it when the view model notify a change.<ref>http://books.zkoss.org/zk-mvvm-book/8.0/syntax/load.html</ref>
 
*@save will not load anything in the view, but will save the values from the view into the view model when updated.<ref>http://books.zkoss.org/zk-mvvm-book/8.0/syntax/save.html</ref>
 
*@bind is basically @save plus @load. Values will be updated from and to the view model when necessary.<ref>http://books.zkoss.org/zk-mvvm-book/8.0/syntax/bind.html</ref>
 
By expensiveness, they are ranked as follow: @init < @load | @save < @bind.
 
<br/>
 
;Do:
 
*Choose the least expensive option for each binding.
 
<br/>
 
;Don’t:
 
*Bind a value using @save or @bind on components whose value cannot be set by the user, such as label, etc.
 
*Bind a value using @load or @bind on components whose value is never set on server side.
 
*Use @load when @init is sufficient.
 
  
==Notifying the whole ListModel on change==
+
== Adding the Bootstrap Resources ==
Speaking of models and data-binding, ListModels will automatically update the view after many actions, such as adding or deleting an element. This makes adding new entries in a complex control such as a grid very easy.
 
However, it’s not always best to refresh the whole model after making a small update on one of its items. ListModels can actually update individual items, which can save a lot of resources.
 
<br/>
 
;Do:
 
*Bind a ListModel to a component using @init, unless you need to replace the whole model by a new object.
 
*Use the ListModelList.notifyChange(…) method to update a single entry, or set the entry again to trigger a refresh instead of notifying the whole model.
 
<br/>
 
;Don’t:
 
*Use @NotifyChange(“*”),  or BindUtils.postNotifyChange(…, …, …, "*"); unless there is no better option.
 
*Use @NotifyChange(“myListModel”) or BindUtils.postNotifyChange(…, …, …, "myListModel"); to update a single row.
 
  
= References =  
+
It's straight forward: just add the required css/js resources. ZK offers several ways to do so:
<references/>
+
* [http://books.zkoss.org/wiki/ZUML_Reference/ZUML/Processing_Instructions/script script] / [http://books.zkoss.org/wiki/ZUML_Reference/ZUML/Processing_Instructions/link link] directives
 +
* [http://books.zkoss.org/wiki/ZK_Component_Reference/Essential_Components/Script script] / [http://books.zkoss.org/wiki/ZK_Component_Reference/Essential_Components/Style style] components
 +
* [http://books.zkoss.org/wiki/ZK_Client-side_Reference/Language_Definition/javascript javascript] / [http://books.zkoss.org/wiki/ZK_Client-side_Reference/Language_Definition/stylesheet stylesheet] elements in a lang-addon.xml
 +
* [http://books.zkoss.org/wiki/ZK_Configuration_Reference/zk.xml/The_device-config_Element/The_embed_Element embed element in zk.xml]
 +
For simplicity's sake, I just added them to my root page.
 +
 
 +
;/wizardexample/src/main/webapp/order.zul [https://github.com/zkoss-demo/zk-wizard-example/blob/part-4/src/main/webapp/order.zul]
 +
 
 +
<source lang="xml" highlight="2,4">
 +
  <!-- Latest compiled and minified CSS -->
 +
  <?link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" ?>
 +
  <!-- Latest compiled and minified JavaScript -->
 +
  <?script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" ?>
 +
</source>
 +
 
 +
Of course, in a real application, you'll likely choose to include the css/js files in your web application (not the topic here).
 +
 
 +
== Render the UI in Bootstrap Style ==
 +
 
 +
Once the layout has been decided (in the ideal case a web designer decided for you and provided static html mockups), you can change your zul files accordingly.
 +
 
 +
Here I'll '''not''' try to make all ZK components look "like" Bootstrap, instead I'll use [[ZK_Component_Reference/XHTML_Components | XHTML components]] and [[ZUML_Reference/ZUML/Namespaces/Native | native elements]] to produce the HTML necessary for Bootstrap. This allows you to use and update the 3rd-party css styles directly whenever needed (or even apply different bootstrap themes later).
 +
 
 +
ZK8's reusable templates and shadow elements help again to avoid repeating the more verbose HTML markup.
 +
If necessary the markup structure of an existing ZK component can be adjusted using a [[ZK_Component_Development_Essentials/Creating_a_simple_ZK_Component/Rendering_Widgets/Implementing_Molds | custom mold]] to fit into the desired layout.
 +
 
 +
=== Page/Wizard Layout ===
 +
 
 +
;/wizardexample/src/main/webapp/order.zul [https://github.com/zkoss-demo/zk-wizard-example/blob/part-4/src/main/webapp/order.zul#L9]
 +
 
 +
Here, the [https://getbootstrap.com/css/#overview-container bootstrap css class (container)] - was added to provide a responsive fixed width layout - nothing else worth mentioning here.
 +
 
 +
<source lang="xml" highlight="1">
 +
<x:div class="container"
 +
viewModel="@id('vm') @init('zk.example.order.OrderViewModel')"
 +
validationMessages="@id('vmsgs')"
 +
onBookmarkChange="@command('gotoStep', stepId=event.bookmark)">
 +
...
 +
</source>
 +
 
 +
More interesting are the changes in the wizard template defining the overall look and feel:
 +
 
 +
;/wizardexample/src/main/webapp/WEB-INF/zul/template/wizard/wizard.zul [https://github.com/zkoss-demo/zk-wizard-example/blob/part-4/src/main/webapp/WEB-INF/zul/template/wizard/wizard.zul]
 +
 
 +
One of the straightforward changes is applying the [https://getbootstrap.com/css/#buttons-options bootstrap button styles]:
 +
 
 +
<source lang="xml" >
 +
    <button zclass="btn btn-default" label="@load(wizardVM.backLabel)" onClick="@command(wizardVM.backCommand)" />
 +
    ...
 +
    <button zclass="btn btn-success pull-right" label="@load(wizardVM.nextLabel)" onClick="@command(wizardVM.nextCommand)" />
 +
</source>
 +
 
 +
[[Image:wizard-buttons-before-after.png|frame|original style (left) <-> after bootstrap makeover (right)]]
 +
 
 +
'''NOTE''': I use [http://books.zkoss.org/wiki/ZK_Style_Customization_Guide/Look_and_Feel_Customization/Partial_customize_with_Sclass_and_Zclass zclass instead of sclass] to replace ZK's own button class ('''z-button''') using bootstrap's css-classes ('''btn btn-default ...''').
 +
 
 +
For the progress bar, it was also simple to adapt the [https://getbootstrap.com/components/#progress-label bootstrap progressbar example markup].
 +
The outer <n:div> is rendered using the native namespace, since it does not require dynamic updates, while the inner <x:div> uses an xhtml component to enable data binding on the dynamic style and textContent properties. A notifyChange on the '''progress'''-property in our wizardVM object will automatically adjust the label and progressbar width (triggering the css animation provided by bootstrap).
 +
 
 +
<source lang="xml" highlight="5">
 +
<template name="wizardProgress">
 +
<n:div class="progress">
 +
<x:div class="progress-bar progress-bar-success progress-bar-striped"
 +
style="@load(('width: ' += wizardVM.progress += '%; min-width: 2em;'))"
 +
textContent="@load((wizardVM.progress += '%'))"/>
 +
</n:div>
 +
</template>
 +
</source>
 +
* '''Line 5:''' the '''textContent'''-attribute on XHTML components is a new ZK8 feature to allow dynamic text content directly inside any html tag
 +
 
 +
In a similar fashion a [https://getbootstrap.com/components/#panels bootstrap panel] can be composed (I assume you have noticed the pattern):
 +
 
 +
<source lang="xml">
 +
<div zclass="panel panel-primary"
 +
viewModel="@id('wizardVM') @init(wizardModel)"
 +
validationMessages="@id('vmsgs')"
 +
onOK="@command(wizardVM.nextCommand)">
 +
<n:div class="panel-heading">
 +
<x:h3 class="panel-title" textContent="@load(wizardVM.currentStep.title)"/>
 +
</n:div>
 +
<n:div class="panel-body">
 +
<sh:apply template="@init(empty wrapperTemplate ? 'defaultWizardContentWrapper' : wrapperTemplate)"/>
 +
</n:div>
 +
</div>
 +
</source>
 +
 
 +
=== Basket Layout ===
 +
 
 +
On the basket page the <grid> was replaced by a [https://getbootstrap.com/css/#tables-striped striped bootstrap table].
 +
The shadow element <sh:forEach>  allows you to reuse the same ListModel of BasketItems from the BasketViewModel while only changing the layout and bind expressions. As described above, xhtml and native elements are used to render the markup required by bootstrap.
 +
 
 +
The [[#tooltip | Tooltips]] are enabled using the Bootstrap JS API. More on that below.
 +
 
 +
In order to make the page a little more responsive to browser width changes, the Basket recommendations on the bottom use the [https://getbootstrap.com/css/#grid Bootstrap grid system] to vary the number of recommendations per row at different display sizes:
 +
 
 +
;/wizardexample/src/main/webapp/WEB-INF/zul/order/steps/basket.zul [https://github.com/zkoss-demo/zk-wizard-example/blob/part-4/src/main/webapp/WEB-INF/zul/order/steps/basket.zul#L58-L68]
 +
 
 +
<source lang="xml" highlight="1,3">
 +
<x:div class="row">
 +
<sh:forEach items="@init(basketVM.recommendedItemsModel)">
 +
<x:div class="col-lg-4 col-sm-6">
 +
<x:div class="well well-sm">
 +
<sh:apply template="basketItemLabel" item="@init(each)"/>
 +
<button zclass="btn btn-info btn-xs pull-right" iconSclass="z-icon-shopping-cart"
 +
onClick="@command('addRecommendedItem', item=each)"
 +
ca:data-toggle="tooltip" ca:data-placement="right"
 +
ca:data-title="${i18n:nls('order.basket.add')}"/>
 +
</x:div>
 +
</x:div>
 +
</sh:forEach>
 +
</x:div>
 +
</source>
 +
 
 +
Here are the results:
 +
[[Image:wizard-basket-before-after.png|center|700px|original style (left) <-> after bootstrap makeover (right)]]
 +
 
 +
=== Form Layout ===
 +
 
 +
The remaining pages previously rendered using a <grid> layout are now implemented using [https://getbootstrap.com/css/#forms-horizontal Bootstrap's horizontal form] layout. This achieves the popular look and responsive sizing/positioning of input elements and their labels. The parameters to the <formRow> template remain identical to the previous version, since the model data hasn't changed.
 +
 
 +
<source language="xml" highlight="1, 3">
 +
<x:div class="form-horizontal">
 +
<formRow type="static" label="@init(i18n:nls('order.basket'))" value="@init(savedOrder.basket)"/>
 +
<x:div class="alert alert-info" role="alert" textContent="${i18n:nls('order.shippingAddress.hint')}"/>
 +
<formRow type="textbox" label="@init(i18n:nls('order.shippingAddress.street'))"
 +
value="@ref(order.shippingAddress.street)"
 +
error="@ref(vmsgs['p_shippingAddress.street'])"/>
 +
<formRow type="textbox" label="@init(i18n:nls('order.shippingAddress.city'))"
 +
value="@ref(order.shippingAddress.city)"
 +
error="@ref(vmsgs['p_shippingAddress.city'])"/>
 +
<formRow type="textbox" label="@init(i18n:nls('order.shippingAddress.zipCode'))"
 +
value="@ref(order.shippingAddress.zipCode)"
 +
error="@ref(vmsgs['p_shippingAddress.zipCode'])"/>
 +
</x:div>
 +
</source>
 +
 
 +
*'''Lines 1,3:''' using bootstrap specifc css classes (form-horizontal, alert, alert-info) on xhtml components
 +
 
 +
 
 +
Inside the formRow template the restyling continues. I also chose to display validation errors in using a bootstrap css classes.
 +
 
 +
<source language="xml" highlight="1, 17, 23">
 +
<x:div sclass="@load(empty error ? 'form-group' : 'form-group has-error')">
 +
<sh:choose>
 +
<sh:when test="@load(type eq 'checkbox')">
 +
<n:div class="col-sm-offset-3 col-sm-9">
 +
<sh:apply template="checkbox"/>
 +
</n:div>
 +
</sh:when>
 +
<sh:otherwise>
 +
<x:label class="col-sm-3 control-label" textContent="@init(label)"/>
 +
<n:div class="col-sm-9">
 +
<sh:apply template="@load(type)"/>
 +
</n:div>
 +
</sh:otherwise>
 +
</sh:choose>
 +
</x:div>
 +
<sh:if test="@load(!empty error)">
 +
<x:div sclass="alert alert-danger well-sm" textContent="@load(error)"/>
 +
</sh:if>
 +
 
 +
<template name="checkbox">
 +
<n:div class="checkbox">
 +
<checkbox zclass=" " checked="@bind(value)" onCheck="@command(updateCommand)" label="@load(label)"
 +
mold="formgroup"/>
 +
</n:div>
 +
</template>
 +
 +
<template name="textbox">
 +
<textbox zclass="form-control" value="@bind(value)" onChange="@command(changeCommand)"/>
 +
</template>
 +
...
 +
</source>
 +
*'''Line 1:''' <row> is replaced by a <x:div> with dynamic styling based depending on the presence of an error message
 +
*'''Line 17:''' conditionally output an error using a [https://getbootstrap.com/components/#alerts Bootstrap alert style]
 +
*'''Line 23:''' apply a custom mold to render the checkbox and its label in the markup required by bootstrap
 +
 
 +
[[Image:wizard-form-before-after.png|center|700px|original style (left) <-> after bootstrap makeover (right)]]
 +
 
 +
==== Custom Checkbox Mold ====
 +
 
 +
Since bootstrap requires different html markup to render a checkbox inside a horizontal form, I decided to define a custom '''mold''' for this scenario.
 +
 
 +
The markup requried by Bootstrap.
 +
<source language="xml" highlight="1, 17, 23">
 +
<label>
 +
<input type="checkbox"> Remember me
 +
</label>
 +
</source>
 +
 
 +
The corresponding custom mold implementation in
 +
;/wizardexample/src/main/resources/web/js/zul/wgt/mold/checkbox-formgroup.js [https://github.com/zkoss-demo/zk-wizard-example/blob/part-4/src/main/resources/web/js/zul/wgt/mold/checkbox-formgroup.js]:
 +
<source language="javascript">
 +
function (out) {
 +
var uuid = this.uuid, content = this.domContent_();
 +
out.push('<label', this.domAttrs_(), ' for="', uuid,'-real">',
 +
'<input type="checkbox" id="', uuid, '-real"', this.contentAttrs_(), '/>',
 +
content,'</label>');
 +
}
 +
</source>
 +
 
 +
As [[ZK_Component_Development_Essentials/Creating_a_simple_ZK_Component/Rendering_Widgets/Implementing_Molds | custom mold]] implementation requires some additional knowledge about the internal structure of a ZK widget, I try to use this approach only if necessary. This is an (often forgotten) available option for any ZK widget in case the rendered markup needs to be customized.
 +
 
 +
The new mold is registered in [https://github.com/zkoss-demo/zk-wizard-example/blob/part-4/src/main/resources/metainfo/zk/lang-addon.xml lang-addon.xml].
 +
 
 +
When upgrading to a different ZK version later this may need to be adjusted. On the other hand, it does provide the most efficient way to render custom markup, since it only happens on the client side.
 +
 
 +
== Leverage the Bootstrap JS API ==
 +
 
 +
=== Bootstrap Tooltips ===
 +
 
 +
Bootstrap also offers a Javascript-api to enable dynamic effects. On the basket page I use [https://getbootstrap.com/javascript/#tooltips Bootstrap-tooltips] configured with ZK8's data-handler, which can be used throughout the application by simply adding client-side data-attributes.
 +
 
 +
<source language="xml" highlight="1,4,8">
 +
<zk xmlns:sh="shadow" xmlns:x="xhtml" xmlns:n="native" xmlns:ca="client/attribute" xmlns:z="zk">
 +
...
 +
<button zclass="close" iconSclass="z-icon-times" onClick="@command('removeItem', basketItem=item)"
 +
ca:data-toggle="tooltip" ca:data-placement="right" ca:data-title="${i18n:nls('order.basket.remove')}"/>
 +
...
 +
<button zclass="btn btn-info btn-xs pull-right" iconSclass="z-icon-shopping-cart"
 +
onClick="@command('addRecommendedItem', item=each)"
 +
ca:data-toggle="tooltip" ca:data-placement="right" ca:data-title="${i18n:nls('order.basket.add')}"/>
 +
</source>
 +
 
 +
An alternative to using "ca:data-title" is to use ZK's tooltiptext property which renders into the title attribute of the resulting DOM element. Since tooltip text is a server side attribute, it also allows the data-binding annotations @init/@load.
 +
 
 +
<source language="xml" highlight="2">
 +
<span zclass=" " status="@ref(item.status)" sclass="@load(i18n:nlsSub(status, 'style'))"
 +
ca:data-toggle="tooltip" ca:data-placement="top" tooltiptext="@load(i18n:nls(status))">
 +
</source>
 +
 
 +
=== Implementing the Data-Handler ===
 +
 
 +
Following the Bootstrap [https://getbootstrap.com/javascript/#tooltips-usage JS documentation] the JS call below is necessary to initialize a tooltip for one or more specified DOM elements.
 +
 
 +
<source  language="javascript">
 +
$('#example').tooltip(options)
 +
</source>
 +
 
 +
Since ZK pages are dynamic, the selector needs to be dynamic too - element Ids are generated and on top of that, ZK components may be added at any time into the DOM via AJAX. In such cases, the client-side widget lifecycle event w:onBind is a good hook to initialize JS behavior. Prior to ZK8, this was only possible using a client-side event listener.
 +
 
 +
<source  language="xml">
 +
<zk xmlns:w="client">
 +
    <button w:onBind="jq(this.$n()).tooltip({placement: 'top'})" tooltiptext="my tooltip"/>
 +
</zk>
 +
</source>
 +
 
 +
A simple data-handler configuration could look like this in zk.xml.
 +
 
 +
<source  language="xml">
 +
<data-handler>
 +
<name>tooltip</name>
 +
<script>
 +
function (wgt, placement) {
 +
jq(wgt.$n()).tooltip({placement: placement});
 +
}
 +
</script>
 +
</data-handler>
 +
</source>
 +
 
 +
And the usage in a zul file.
 +
<source  language="xml">
 +
<zk xmlns:w="client/attribute">
 +
    <button ca:data-tooltip="top" tooltiptext="my tooltip"/>
 +
</zk>
 +
</source>
 +
 
 +
While this can be used in any page throughout the application, it is still quite limiting and not taking full advantage of the Bootstrap JS API (e.g. new parameters have to be added manually on by one).
 +
Since many Bootstrap and other JS effects are "toggled" in a similar way, we can configure a data-handler that covers those at once.
 +
 
 +
<source language="xml" highlight="5">
 +
<data-handler>
 +
<name>toggle</name>
 +
<script>
 +
function (wgt, dataValue) {
 +
jq(wgt.$n())[dataValue]();
 +
}
 +
</script>
 +
</data-handler>
 +
</source>
 +
*'''Line 5:''' calls a JQuery function by its name (dataValue contains the function name, in this case 'tooltip')
 +
 
 +
This enables the following usage and enables other effects to be enabled with the same data-handler (e.g. modal dialogs see next chapter).
 +
<source  language="xml">
 +
<zk xmlns:w="client/attribute">
 +
    <button ca:data-toggle="tooltip" ca:data-placement="top" ca:data-title="my tooltip"/>
 +
</zk>
 +
</source>
 +
 
 +
This way any "data-*" attributes supported by the tooltip API can be used.
 +
 
 +
=== Bootstrap Modal ===
 +
Using the same generic data-handler from above, the modal dialog integration is already showing the modal dialog.
 +
 
 +
The custom [[http://books.zkoss.org/wiki/ZK_Developer's_Reference/UI_Patterns/Error_Handling#Error_Handling_When_Serving_AU_Requests error page is configured in zk.xml]], different errors can load different dialogs, here I handle the OrderExceptions (thrown when a payment method is not available)
 +
 
 +
<source lang="xml" highlight="2">
 +
<error-page>
 +
<exception-type>zk.example.order.api.OrderException</exception-type>
 +
<location>/WEB-INF/zul/order/error/orderError.zul</location>
 +
</error-page>
 +
</source>
 +
 
 +
;/wizardexample/src/main/webapp/WEB-INF/zul/order/error/orderError.zul [https://github.com/zkoss-demo/zk-wizard-example/blob/part-4/src/main/webapp/WEB-INF/zul/order/error/orderError.zul#L2]
 +
 
 +
<source lang="xml" highlight="2">
 +
<zk xmlns:ca="client/attribute" xmlns:z="zul" xmlns:x="xhtml">
 +
<div sclass="modal fade" ca:data-toggle="modal" ca:data-close-event="hidden.bs.modal" onModalClose="self.detach()" >
 +
<div xmlns="native" class="modal-dialog">
 +
...
 +
</div><!-- /.modal-dialog -->
 +
</div><!-- /.modal -->
 +
</zk>
 +
</source>
 +
 
 +
[[Image:wizard-modal-before-after.png|center|700px|original style (left) <-> after bootstrap makeover (right)]]
 +
 
 +
In order to close the modal dialog I registered another data-handler, which will listen to the "hidden.bs.modal" event (triggered when the modal dialog has been closed and the fade out animation has finished). It then fire the onModalClose to the server side to detach the dialog.
 +
 
 +
<source lang="xml" highlight="2">
 +
<data-handler>
 +
<name>close-event</name>
 +
<script>
 +
function (wgt, dataValue) {
 +
jq(wgt.$n()).on(dataValue, function() {
 +
wgt.fire("onModalClose", null, {toServer: true});
 +
});
 +
}
 +
</script>
 +
</data-handler>
 +
</source>
 +
 
 +
I know using an inline event listener is a cheap shortcut here, but performance was not a concern in this example, especially when handling exceptions (as the name says this should be an '''exceptional''' and not the regular case).
 +
Alternatives are to apply a Composer and listen to the event inside a java class and destroy the error dialog. If further details are required, please let me know in the comments section below.
 +
 
 +
= Summary =
 +
 
 +
That's it for now, any ideas what to show next? Waiting for your comments.
 +
 
 +
== Download ==
 +
* The source code for this article can be found in [https://github.com/zkoss-demo/zk-wizard-example/tree/part-4 github (branch: part-4)].
 +
 
 +
== Running the Example ==
 +
Checkout '''part-4'''
 +
 
 +
    git checkout part-4
 +
 
 +
The example war file can be built with maven:
 +
 
 +
    mvn clean package
 +
 
 +
Execute using jetty:
 +
 
 +
    mvn jetty:run
 +
 
 +
Then access the overview page http://localhost:8080/wizardexample/order.zul
  
 
{{Template:CommentedSmalltalk_Footer_new|
 
{{Template:CommentedSmalltalk_Footer_new|
 
|name=Potix Corporation
 
|name=Potix Corporation
 
}}
 
}}
 +
 +
[[Category:Small Talk]]

Latest revision as of 07:54, 20 January 2022

The Name Of My Page

Author
Robert Wenzel, Engineer, Potix Corporation
Date
April 2016
Version
ZK 8.0

Introduction

To wrap up the Wizard Example Series, here is the final Part showing how things finally fit together when applying a 3rd party CSS framework (Bootstrap) to the wizard.

The implementation decisions/techniques used in the previous chapters now become handy. The strict separation between view and viewModel code enables the style overhaul without touching any Java code. Restyling an application still requires a significant amount of work, in which the major task is to adjust the various zul pages and templates to render the markup required by Bootstrap. However, compared to changing both zul and java code, the possibility of introducing errors is much smaller (and even if new problems arise, they are obviously somewhere in the view).

Here is a recording of the results (descriptions of the most significant changes will follow below):

Adding the Bootstrap Resources

It's straight forward: just add the required css/js resources. ZK offers several ways to do so:

For simplicity's sake, I just added them to my root page.

/wizardexample/src/main/webapp/order.zul [1]
  <!-- Latest compiled and minified CSS -->
  <?link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" ?>
  <!-- Latest compiled and minified JavaScript -->
  <?script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" ?>

Of course, in a real application, you'll likely choose to include the css/js files in your web application (not the topic here).

Render the UI in Bootstrap Style

Once the layout has been decided (in the ideal case a web designer decided for you and provided static html mockups), you can change your zul files accordingly.

Here I'll not try to make all ZK components look "like" Bootstrap, instead I'll use XHTML components and native elements to produce the HTML necessary for Bootstrap. This allows you to use and update the 3rd-party css styles directly whenever needed (or even apply different bootstrap themes later).

ZK8's reusable templates and shadow elements help again to avoid repeating the more verbose HTML markup. If necessary the markup structure of an existing ZK component can be adjusted using a custom mold to fit into the desired layout.

Page/Wizard Layout

/wizardexample/src/main/webapp/order.zul [2]

Here, the bootstrap css class (container) - was added to provide a responsive fixed width layout - nothing else worth mentioning here.

<x:div class="container"
	 viewModel="@id('vm') @init('zk.example.order.OrderViewModel')" 
	 validationMessages="@id('vmsgs')"
	 onBookmarkChange="@command('gotoStep', stepId=event.bookmark)">
...

More interesting are the changes in the wizard template defining the overall look and feel:

/wizardexample/src/main/webapp/WEB-INF/zul/template/wizard/wizard.zul [3]

One of the straightforward changes is applying the bootstrap button styles:

    <button zclass="btn btn-default" label="@load(wizardVM.backLabel)" onClick="@command(wizardVM.backCommand)" />
    ...
    <button zclass="btn btn-success pull-right" label="@load(wizardVM.nextLabel)" onClick="@command(wizardVM.nextCommand)" />
original style (left) <-> after bootstrap makeover (right)

NOTE: I use zclass instead of sclass to replace ZK's own button class (z-button) using bootstrap's css-classes (btn btn-default ...).

For the progress bar, it was also simple to adapt the bootstrap progressbar example markup. The outer <n:div> is rendered using the native namespace, since it does not require dynamic updates, while the inner <x:div> uses an xhtml component to enable data binding on the dynamic style and textContent properties. A notifyChange on the progress-property in our wizardVM object will automatically adjust the label and progressbar width (triggering the css animation provided by bootstrap).

	<template name="wizardProgress">
		<n:div class="progress">
			<x:div class="progress-bar progress-bar-success progress-bar-striped" 
				style="@load(('width: ' += wizardVM.progress += '%; min-width: 2em;'))"
				textContent="@load((wizardVM.progress += '%'))"/>
		</n:div>
	</template>
  • Line 5: the textContent-attribute on XHTML components is a new ZK8 feature to allow dynamic text content directly inside any html tag

In a similar fashion a bootstrap panel can be composed (I assume you have noticed the pattern):

	<div zclass="panel panel-primary"
			viewModel="@id('wizardVM') @init(wizardModel)"
			validationMessages="@id('vmsgs')"
			onOK="@command(wizardVM.nextCommand)">
		<n:div class="panel-heading">
			<x:h3 class="panel-title" textContent="@load(wizardVM.currentStep.title)"/>
		</n:div>
		<n:div class="panel-body">
			<sh:apply template="@init(empty wrapperTemplate ? 'defaultWizardContentWrapper' : wrapperTemplate)"/>
		</n:div>
	</div>

Basket Layout

On the basket page the <grid> was replaced by a striped bootstrap table. The shadow element <sh:forEach> allows you to reuse the same ListModel of BasketItems from the BasketViewModel while only changing the layout and bind expressions. As described above, xhtml and native elements are used to render the markup required by bootstrap.

The Tooltips are enabled using the Bootstrap JS API. More on that below.

In order to make the page a little more responsive to browser width changes, the Basket recommendations on the bottom use the Bootstrap grid system to vary the number of recommendations per row at different display sizes:

/wizardexample/src/main/webapp/WEB-INF/zul/order/steps/basket.zul [4]
<x:div class="row">
	<sh:forEach items="@init(basketVM.recommendedItemsModel)">
		<x:div class="col-lg-4 col-sm-6">
			<x:div class="well well-sm">
				<sh:apply template="basketItemLabel" item="@init(each)"/>
				<button zclass="btn btn-info btn-xs pull-right" iconSclass="z-icon-shopping-cart" 
					onClick="@command('addRecommendedItem', item=each)" 
					ca:data-toggle="tooltip" ca:data-placement="right" 
					ca:data-title="${i18n:nls('order.basket.add')}"/>
			</x:div>
		</x:div>
	</sh:forEach>
</x:div>

Here are the results:

original style (left) <-> after bootstrap makeover (right)

Form Layout

The remaining pages previously rendered using a <grid> layout are now implemented using Bootstrap's horizontal form layout. This achieves the popular look and responsive sizing/positioning of input elements and their labels. The parameters to the <formRow> template remain identical to the previous version, since the model data hasn't changed.

	<x:div class="form-horizontal">
		<formRow type="static" label="@init(i18n:nls('order.basket'))" value="@init(savedOrder.basket)"/> 
		<x:div class="alert alert-info" role="alert" textContent="${i18n:nls('order.shippingAddress.hint')}"/>
		<formRow type="textbox" label="@init(i18n:nls('order.shippingAddress.street'))" 
			value="@ref(order.shippingAddress.street)"
			error="@ref(vmsgs['p_shippingAddress.street'])"/> 
		<formRow type="textbox" label="@init(i18n:nls('order.shippingAddress.city'))" 
			value="@ref(order.shippingAddress.city)" 
			error="@ref(vmsgs['p_shippingAddress.city'])"/> 
		<formRow type="textbox" label="@init(i18n:nls('order.shippingAddress.zipCode'))" 
			value="@ref(order.shippingAddress.zipCode)"
			error="@ref(vmsgs['p_shippingAddress.zipCode'])"/> 
	</x:div>
  • Lines 1,3: using bootstrap specifc css classes (form-horizontal, alert, alert-info) on xhtml components


Inside the formRow template the restyling continues. I also chose to display validation errors in using a bootstrap css classes.

	<x:div sclass="@load(empty error ? 'form-group' : 'form-group has-error')">
		<sh:choose>
			<sh:when test="@load(type eq 'checkbox')">
				<n:div class="col-sm-offset-3 col-sm-9">
					<sh:apply template="checkbox"/>
				</n:div>
			</sh:when>
			<sh:otherwise>
				<x:label class="col-sm-3 control-label" textContent="@init(label)"/>
				<n:div class="col-sm-9">
					<sh:apply template="@load(type)"/>
				</n:div>
			</sh:otherwise>
		</sh:choose>
	</x:div>
	<sh:if test="@load(!empty error)">
		<x:div sclass="alert alert-danger well-sm" textContent="@load(error)"/>
	</sh:if>

	<template name="checkbox">
		<n:div class="checkbox">
			<checkbox zclass=" " checked="@bind(value)" onCheck="@command(updateCommand)" label="@load(label)" 
				mold="formgroup"/>
		</n:div>
	</template>
	
	<template name="textbox">
		<textbox zclass="form-control" value="@bind(value)" onChange="@command(changeCommand)"/>
	</template>
	 ...
  • Line 1: <row> is replaced by a <x:div> with dynamic styling based depending on the presence of an error message
  • Line 17: conditionally output an error using a Bootstrap alert style
  • Line 23: apply a custom mold to render the checkbox and its label in the markup required by bootstrap
original style (left) <-> after bootstrap makeover (right)

Custom Checkbox Mold

Since bootstrap requires different html markup to render a checkbox inside a horizontal form, I decided to define a custom mold for this scenario.

The markup requried by Bootstrap.

	<label>
		<input type="checkbox"> Remember me
	</label>

The corresponding custom mold implementation in

/wizardexample/src/main/resources/web/js/zul/wgt/mold/checkbox-formgroup.js [5]
function (out) {
	var uuid = this.uuid, content = this.domContent_();
	out.push('<label', this.domAttrs_(), ' for="', uuid,'-real">',
			 '<input type="checkbox" id="', uuid, '-real"', this.contentAttrs_(), '/>',
			 content,'</label>');
}

As custom mold implementation requires some additional knowledge about the internal structure of a ZK widget, I try to use this approach only if necessary. This is an (often forgotten) available option for any ZK widget in case the rendered markup needs to be customized.

The new mold is registered in lang-addon.xml.

When upgrading to a different ZK version later this may need to be adjusted. On the other hand, it does provide the most efficient way to render custom markup, since it only happens on the client side.

Leverage the Bootstrap JS API

Bootstrap Tooltips

Bootstrap also offers a Javascript-api to enable dynamic effects. On the basket page I use Bootstrap-tooltips configured with ZK8's data-handler, which can be used throughout the application by simply adding client-side data-attributes.

<zk xmlns:sh="shadow" xmlns:x="xhtml" xmlns:n="native" xmlns:ca="client/attribute" xmlns:z="zk">
...
<button zclass="close" iconSclass="z-icon-times" onClick="@command('removeItem', basketItem=item)"
	ca:data-toggle="tooltip" ca:data-placement="right" ca:data-title="${i18n:nls('order.basket.remove')}"/>
... 
<button zclass="btn btn-info btn-xs pull-right" iconSclass="z-icon-shopping-cart" 
	onClick="@command('addRecommendedItem', item=each)" 
	ca:data-toggle="tooltip" ca:data-placement="right" ca:data-title="${i18n:nls('order.basket.add')}"/>

An alternative to using "ca:data-title" is to use ZK's tooltiptext property which renders into the title attribute of the resulting DOM element. Since tooltip text is a server side attribute, it also allows the data-binding annotations @init/@load.

<span zclass=" " status="@ref(item.status)" sclass="@load(i18n:nlsSub(status, 'style'))" 
	ca:data-toggle="tooltip" ca:data-placement="top" tooltiptext="@load(i18n:nls(status))">

Implementing the Data-Handler

Following the Bootstrap JS documentation the JS call below is necessary to initialize a tooltip for one or more specified DOM elements.

 $('#example').tooltip(options)

Since ZK pages are dynamic, the selector needs to be dynamic too - element Ids are generated and on top of that, ZK components may be added at any time into the DOM via AJAX. In such cases, the client-side widget lifecycle event w:onBind is a good hook to initialize JS behavior. Prior to ZK8, this was only possible using a client-side event listener.

<zk xmlns:w="client">
    <button w:onBind="jq(this.$n()).tooltip({placement: 'top'})" tooltiptext="my tooltip"/>
</zk>

A simple data-handler configuration could look like this in zk.xml.

<data-handler>
	<name>tooltip</name>
	<script>
		function (wgt, placement) {
			jq(wgt.$n()).tooltip({placement: placement});
		}
	</script>
</data-handler>

And the usage in a zul file.

<zk xmlns:w="client/attribute">
    <button ca:data-tooltip="top" tooltiptext="my tooltip"/>
</zk>

While this can be used in any page throughout the application, it is still quite limiting and not taking full advantage of the Bootstrap JS API (e.g. new parameters have to be added manually on by one). Since many Bootstrap and other JS effects are "toggled" in a similar way, we can configure a data-handler that covers those at once.

	<data-handler>
		<name>toggle</name>
		<script>
			function (wgt, dataValue) {
				jq(wgt.$n())[dataValue]();
			}
		</script>
	</data-handler>
  • Line 5: calls a JQuery function by its name (dataValue contains the function name, in this case 'tooltip')

This enables the following usage and enables other effects to be enabled with the same data-handler (e.g. modal dialogs see next chapter).

<zk xmlns:w="client/attribute">
    <button ca:data-toggle="tooltip" ca:data-placement="top" ca:data-title="my tooltip"/>
</zk>

This way any "data-*" attributes supported by the tooltip API can be used.

Bootstrap Modal

Using the same generic data-handler from above, the modal dialog integration is already showing the modal dialog.

The custom [error page is configured in zk.xml], different errors can load different dialogs, here I handle the OrderExceptions (thrown when a payment method is not available)

	<error-page>
		<exception-type>zk.example.order.api.OrderException</exception-type>
		<location>/WEB-INF/zul/order/error/orderError.zul</location>
	</error-page>
/wizardexample/src/main/webapp/WEB-INF/zul/order/error/orderError.zul [6]
<zk xmlns:ca="client/attribute" xmlns:z="zul" xmlns:x="xhtml">
	<div sclass="modal fade" ca:data-toggle="modal" ca:data-close-event="hidden.bs.modal" onModalClose="self.detach()" >
		<div xmlns="native" class="modal-dialog">
		...
		</div><!-- /.modal-dialog -->
	</div><!-- /.modal -->
</zk>
original style (left) <-> after bootstrap makeover (right)

In order to close the modal dialog I registered another data-handler, which will listen to the "hidden.bs.modal" event (triggered when the modal dialog has been closed and the fade out animation has finished). It then fire the onModalClose to the server side to detach the dialog.

	<data-handler>
		<name>close-event</name>
		<script>
			function (wgt, dataValue) {
				jq(wgt.$n()).on(dataValue, function() {
					wgt.fire("onModalClose", null, {toServer: true});
				});
			}
		</script>
	</data-handler>

I know using an inline event listener is a cheap shortcut here, but performance was not a concern in this example, especially when handling exceptions (as the name says this should be an exceptional and not the regular case). Alternatives are to apply a Composer and listen to the event inside a java class and destroy the error dialog. If further details are required, please let me know in the comments section below.

Summary

That's it for now, any ideas what to show next? Waiting for your comments.

Download

Running the Example

Checkout part-4

   git checkout part-4

The example war file can be built with maven:

   mvn clean package

Execute using jetty:

   mvn jetty:run

Then access the overview page http://localhost:8080/wizardexample/order.zul


Comments



Copyright © Potix Corporation. This article is licensed under GNU Free Documentation License.