Integrate ZK with dhtmlxGantt"

From Documentation
Line 17: Line 17:
  
 
= Demo =
 
= Demo =
 +
 +
<gflash width="800">GanttChartDemo.swf</gflash>
  
 
= Prerequisites =
 
= Prerequisites =

Revision as of 02:58, 15 October 2014




WarningTriangle-32x32.png This page is under construction, so we cannot guarantee the accuracy of the content!

DocumentationSmall Talks2014OctoberIntegrate ZK with dhtmlxGantt
Integrate ZK with dhtmlxGantt

Author
Vincent Jian, Engineer, Potix Corporation
Date
October 7, 2014
Version
ZK 7.0.3, dhtmlxGantt v.3.0.0 Standard

Introduction

dhtmlxGantt is an open source JavaScript Gantt chart that helps you visualize a project schedule in a nice-looking chart. It can show the dependencies between tasks as lines and allows you to set up different relationships between tasks (finish-to-start, start-to-start, end-to-end). This smalltalk will introduce how you can integrate dhtmlxGantt into an ZK web application, step by step. By following this example you should be able to get an overview on how 3rd party integration in ZK is done and start to integrate any 3rd JS party libraries in ZK as you wish.

Demo

ERROR: Width and Height not set

Prerequisites

Since dhtmlxGantt is a javascript library, here I will use the technical described in the following articles to integrated with ZK:

Before you start to integrate a 3rd party library, it is suggested to read the above two articles to understand the life cycle of ZK client widget.

Steps to integrate dhtmlxGantt

Create ZK Project and Prepare Necessary Libraries

1. Create a ZK project by maven, refer to our installation guide.

2. Download dhtmlxGantt library from its official site, here I download the version 3.0 standard edition (GNU GPL v2 license).

  • Extract the zip file and put dhtmlxgantt.js and dhtmlxgantt.css files under the project's "webapp/gantt" folder.

Load the library source and setup basic component

To load the dhtmlxgantt library, we can use script xml processing instructions such as <?link?> and <?script?> on the zul page. According to dhtmlxgantt online document, a simple div element is enough to initialize Gantt chart. Therefore, we add a div component on the zul page as follows.

<?link rel="stylesheet" type="text/css" href="/gantt/dhtmlxgantt.css"?>
<?script type="text/javascript" src="/gantt/dhtmlxgantt.js"?>
<zk>
    <window title="Dhtml Gantt Integration" border="normal" vflex="1">
        <div id="gantt" />
    </window>
</zk>
  • Line 1,2: Load dhtmlxgantt library
  • Line 5: Add div component to generate Gantt Chart.

Prepare data for Gantt Chart

Normally, a Gantt Chart need gantt tasks and gantt dependency links, and from dhtmlxGantt's online document, we can see a list of available properties for gantt task and gantt link. Based on which, we need to create two Java Objects as follows:

public class GanttTask implements JSONAware {

    private long id;
    private Date startDate;
    private int duration;
    private String description;
    private double progress;
    private int sortOrder;
    private GanttTask parent;
    private boolean open;

    public String toJSONString() {
        DateFormat dft = new SimpleDateFormat("dd-MM-yyyy");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("start_date", dft.format(startDate));
        map.put("duration", duration);
        map.put("text", description);
        map.put("progress", progress);
        map.put("sortorder", sortOrder);
        map.put("parent", parent == null ? 0 : parent.getId());
        map.put("open", open);
        return JSONObject.toJSONString(map);
    }

    /* getter and setter omitted */
}
public class GanttLink implements JSONAware {

    private long id;
    private GanttTask source;
    private GanttTask target;
    private int type;

    public String toJSONString() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("source", source.getId());
        map.put("target", target.getId());
        map.put("type", type);
        return JSONObject.toJSONString(map);
    }

    /* getter and setter omitted */
}

As dhtmlxGantt supports load JSON format objects, here we implement JSONAware.

Wrap dhtmlxgantt library with ZK Client Widget

Before we load the real data, we will create a new widget that extends div widget and use bind_ life-cycle to register Gantt Event. And we prepare extra APIs such as "_init", "_attachGanttEvent" and "_detachGanttEvent" that are only used for Gantt Chart.

zk.afterLoad('zul.wgt', function() {
    zul.wgt.GanttDiv = zk.$extends(zul.wgt.Div, {
        bind_: function() {
            this.$supers('bind_', arguments);
            // attach gantt event
            this._attachGanttEvent();
        },
        unbind_: function() {
            this._detachGanttEvent();
            this.$supers('unbind_', arguments);
        },
        _init: function(task) {
            gantt.init(this.uuid); //let dhmltxGantt library know where to render Gantt Chart
            gantt.parse(task);  //parse task and render Gantt Chart
        }
        _attachGanttEvent: function() {
            // attach Gantt Event here
        },
        _detachGanttEvent: function() {
            // detach Gantt Event here
        }
    }
});
  • Line 2: Create GanttDiv widget that extends Div widget.
  • Line 6: Attach Gantt Event.
  • Line 12: "_init" API that will be used for initializing Gantt chart from server side.
  • Line 16, 19: Attach and detach Gantt Event for communication between client and server.

Then we apply this widget by client widget attribute "use" in zul page we created earlier as follows:

<zk xmlns:w="client">
    <window title="Dhtml Gantt Integration" border="normal" vflex="1">
        <div id="gantt" w:use="zul.wgt.GanttDiv" />
    </window>
<zk>
  • Line 3: Define the name space prefix "w" for client widget attribute.
  • Line 5: Apply GanttDiv widget to the div component.

Loading data from server to dhtmlxGantt library

Here we use MVC pattern to load data from server side as follows:

1. Apply GanttComposer to window component.

<window title="Dhtml Gantt Integration" border="normal" vflex="1" apply="org.zkoss.sample.GanttComposer">
    <div id="gantt" w:use="zul.wgt.GanttDiv" />
</window>

2. Here we create some dummy tasks and links and call the GanttDiv widget's init function we added in previous section by Clients.response(AuResponse) API. With which dhtmlxgantt library parses the tasks and draws gantt chart.

public class GanttComposer extends SelectorComposer<Component> {

    @Wire
    private Div gantt;

    private List<GanttTask> taskList;
    private List<GanttLink> linkList;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
        taskList = new ArrayList<GanttTask>();
        linkList = new ArrayList<GanttLink>();
        String[] ganttJSONString = initGanttTasks();

        Clients.response(new AuInvoke(gantt, "_init",
                "{\"data\": [" + ganttJSONString[0] + "], " +
                "\"collections\": {\"links\": [" + ganttJSONString[1] + "]}}"));
    }

    private String[] initGanttTasks() {
        Calendar cal = Calendar.getInstance();
        
        cal.set(2013, 3, 1);
        GanttTask parent = new GanttTask(1L, cal.getTime(), 5, "Project #1", 0.8, 20, null, true);
        taskList.add(parent);
        String taskJSONString = parent.toJSONString();
        // omitted other tasks
        
        GanttLink link1 = new GanttLink(1L, parent, task1, 0);
        linkList.add(link1);
        String linkJSONString = link1.toJSONString();
        // omitted other links
        
        return new String[]{taskJSONString, linkJSONString};
    }
}
  • Line 14: Create dummy tasks and links.
  • Line 16-18: Execute GanttDiv widget's _init function to parse tasks and draw gantt chart.

Send dhtmlxGantt event back to server

dhtmlxGantt library provides great UI to add other tasks and links and provide correspond event to register, such as onAfterTaskAdd and onAfterLinkAdd, refer to the its online document for complete event list. This section will show how to register these events and send the events back to server.

First, we register gantt task and link related events in the GanttDiv widget and new a ZK event to send the updated task and link to server as follows:

_attachGanttEvent: function() {
    var self = this;
    gantt.attachEvent('onAfterTaskAdd', function(id, item) {
        zAu.send(new zk.Event(self, "onTaskAdd", {'' : item}, {toServer:true}));
    });
    gantt.attachEvent('onAfterTaskUpdate', function(id, item) {
        zAu.send(new zk.Event(self, "onTaskUpdate", {'' : item}, {toServer:true}));
    });
        gantt.attachEvent('onAfterTaskDelete', function(id, item) {
        zAu.send(new zk.Event(self, "onTaskDelete", {'' : item}, {toServer:true}));
    });

    gantt.attachEvent('onAfterLinkAdd', function(id, item) {
        zAu.send(new zk.Event(self, 'onLinkAdd', {'' : item}, {toServer:true}));
    });
    gantt.attachEvent('onAfterLinkDelete', function(id, item) {
        zAu.send(new zk.Event(self, 'onLinkDelete', {'' : item}, {toServer:true}));
    });
},
_detachGanttEvent: function() {
    gantt.detachAllEvents();
}
  • Line 19: new ZK event with option "toServer: true" to make sure this event will send to server side, then send the event by zAu.send() API.

Then, we listen onTaskAdd event in our composer to receive the event as follows:

public class GanttComposer extends SelectorComposer<Component> {
    @Listen("onTaskAdd = #gantt")
    public void addTask(Event evt) throws ParseException {
        JSONObject obj = (JSONObject) evt.getData();
        GanttTask task = new GanttTask();
        // parse obj to task
        task.setId((Long) obj.get("id"));
        // omit other fields
        // add task to list/DB
        taskList.add(task);
    }
}

Conclusion

This article takes dhtmlxGantt chart as an example to demonstrate how easy it is to integrate a fancy 3rd party library in ZK. By applying the same methods you should be able to integrate any 3rd party libraries as you wish!

Download

You can fork the project from github. Note that the purpose of this article is to demonstrate how you can integrate a 3rd party library with ZK. If you wish to use the resulting integration, you will need to consult with the 3rd party provider (i.e. DHTMLX) to obtain appropriate license.


Comments



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