Wednesday, September 21, 2011

DHTMLX Tags on Gaelyk


About a month ago the final release of Gaelyk 1.0, the lightweight Groovy toolkit for Google App Engine, has been released. I'm a fan of the Groovy programming language, even if it is challenging to involve customers in this paradigm shift. This post illustrates a simple CRUD  application, (available here), written with Gaelyk and the DHTMLX Tag libraryThere is a school of thought that considers tag libraries to be evil and another one which does not. Between the two schools there are those who believe that tag libraries can be useful, if you don't turn them into a monster. In a discussion about Gaelyk and tag libraries support, Guillaume Laforge, made a very smart point about this subject (see here):
Gaelyk templates are really just one view option. You can still continue using Groovlets, but delegate to JSP views, using JSP taglibs. Gaelyk doesn't try to reinvent the wheel here
Gaelyk provides templates (GTPL)  similar to JSPs, which are pages containing scriptlets of code. In the same way in which you can mix Java and Groovy code for classes, Gaelyk let you use a combination of GTPL and JSP pages. 
In this sample application there are two pages, the first one based on a dhtmlxGrid,  which presents the list of records, and second uses a dhtmlxForm to display and edit the data.See screenshot here
Both pages have been created using the DHTMLX Tag Designer, which makes it pretty simple to prototype the layout. 
To take the advantage of Gaelyk templates the JSPs are included within the GTPL: 


war/WEB-INF/pages/index.gtpl
  1. <% include '/WEB-INF/includes/header.gtpl' %>
  2. <% include '/WEB-INF/jsp/list.jsp' %>
  3. <% include '/WEB-INF/includes/footer.gtpl' %>


war/WEB-INF/pages/edit.gtpl
  1. <% include '/WEB-INF/includes/header.gtpl' %>
  2. <% include '/WEB-INF/jsp/form.jsp' %>
  3. <% include '/WEB-INF/includes/footer.gtpl' %>


The section about the grid page is missing, because it is  very similar to a previous post, and the focus here is on the form based edit page. The source code is below:

war/WEB-INF/jsp/form.jsp
  1. <%@ taglib uri="http://www.mylaensys.com/dhtmlx" prefix="dhtmlx" %>
  2. <dhtmlx:body name='initializeDHTMLX' imagePath='/imgs/'>
  3.   <dhtmlx:layout name='layout' id='content' pattern='1C'>
  4.      <dhtmlx:layoutcell name='a' text='a' i18n='false' hideHeader='true'>
  5.         <dhtmlx:toolbar name='toolbar'>
  6.            <dhtmlx:toolbarButton id='button_list' text='List'/>
  7.             </dhtmlx:toolbar>
  8.             <dhtmlx:form name='form'>
  9.               <dhtmlx:formInputFieldSet name='fieddset' label='Book Edit'>
  10.                   <dhtmlx:formHidden name='id' value="0"/>
  11.                   <dhtmlx:formLabel name="message" label=""/>
  12.                   <dhtmlx:formInput name='author' label='Author'/>
  13.                   <dhtmlx:formInput name='price' label='Price'/>
  14.                   <dhtmlx:formInput name='sales' label='Sales'/>
  15.                   <dhtmlx:formInput name='title' label='Title'/>
  16.                   <dhtmlx:formButton name='button_upd' value='Update'/>
  17.               </dhtmlx:formInputFieldSet>
  18.             </dhtmlx:form>
  19.         </dhtmlx:layoutcell>
  20.     </dhtmlx:layout>
  21. </dhtmlx:body>
  22. <script language='JavaScript' type='text/javascript'>
  23.     var errorMessage = "";
  24.     var bookId = '<%= request.getAttribute("id") %>';
  25.     function custom_NotEmpty(value) {
  26.         if (!dhtmlxValidation.isNotEmpty(value)) {
  27.             return " must not be empty";
  28.         }
  29.         return true;
  30.     }
  31.     function custom_ValidNumeric(value) {
  32.         if (!dhtmlxValidation.isValidNumeric(value)) {
  33.             return "must be a numeric";
  34.         }
  35.         return true;
  36.     }
  37.     function custom_ValidInteger(value) {
  38.         if (!dhtmlxValidation.isValidInteger(value)) {
  39.             return "must be an integer";
  40.         }
  41.         return true;
  42.     }
  43.     function initialize() {
  44.         initializeDHTMLX();
  45.         toolbar.attachEvent("onClick", on_click);
  46.         form.attachEvent("onButtonClick", function(id) {
  47.             if (id == "button_upd") {
  48.                 if (form.validate()) {
  49.                     toolbar.disableItem("button_list");
  50.                     form.setItemLabel('message', '<div class="message">Saving...</div>');
  51.                     form.save();
  52.                 } else {
  53.                     form.setItemLabel('message', '<div class="error">' + errorMessage + '</div>');
  54.                 }
  55.             }
  56.         });
  57.         form.bindValidator("author", "custom_NotEmpty");
  58.         form.bindValidator("price", "custom_ValidNumeric");
  59.         form.bindValidator("sales", "custom_ValidInteger");
  60.         form.bindValidator("title", "custom_NotEmpty");
  61.         form.attachEvent("onBeforeValidate", function() {
  62.             errorMessage = "";
  63.             return true;
  64.         });
  65.         form.attachEvent("onValidateError", function(obj, value, res) {
  66.             errorMessage += obj.name.toUpperCase() + " : " + res + " ";
  67.         });
  68.   
  69.         var dp = new dataProcessor("/book/processor");
  70.         dp.setTransactionMode("POST");
  71.         dp.init(form);
  72.         dp.attachEvent("onAfterUpdate", function(sid, action, tid, tag) {
  73.             form.load("/book/show/" + bookId);
  74.             form.setItemLabel('message', '<div class="message">Record Saved</div>');
  75.             toolbar.enableItem("button_list");
  76.         });
  77.         form.load("/book/show/" + bookId);
  78.     }
  79.     function on_click(id) {
  80.         if ("button_list" == id) {
  81.             window.location.href = encodeURI('/');
  82.         }
  83.     }
  84.     dhtmlxEvent(window, 'load', initialize);
  85. </script>


The initialization attaches a handler to the onButtonClick form button event, which updates the message on top of the form, and posts the save operation to the application. The second step of the code sets up the validation, binding  validators to the object form fields, and provides the onBeforeValidate and onValidateError event handlers to update the text message box.
The final step invokes the load method on the form, it triggers an Ajax call to the book Groovlet to retrieve the data and fill the form. 
The routes.groovy defines the URL mapping :

war/WEB-INF/routes.groovy
  1. get  "/", forward: "/WEB-INF/pages/index.gtpl"
  2. get  "/book/@task/@id", forward: "/book.groovy?id=@id&task=@task"
  3. post "/book/processor", forward: "/processor.groovy"


In the case above, path variables are translated in order to route different task to a single Groovlet. The book.groovy Groovlet performs the list, show and edit operations.

war/WEB-INF/groovy/book.groovy
  1. import com.google.appengine.api.datastore.Entity
  2. import com.google.appengine.api.datastore.Key
  3. import com.google.appengine.api.datastore.KeyFactory
  4. switch (params."task") {
  5.   case "list":
  6.    log.info "list : getting book list "
  7.    int entityCount = datastore.execute { select count from books }
  8.    params.offset = params.posStart ? Integer.parseInt( params.posStart ) : 0
  9.    params.max = params.count ? Integer.parseInt( params.count) : 20
  10.    params.sort
  11. = params.orderby ? params.orderby : "sales"
  12.    params.order = params.dir ? (params.dir == "des" ? "desc" : "asc") : "asc"
  13.         def books = datastore.execute {
  14.             from books
  15.             limit params.max offset params.offset
  16.             sort params.order by params.sort
  17.         }
  18.         response.setContentType("text/xml")
  19.         html.rows(total_count: entityCount , pos: params.offset ) {
  20.             books.each { book ->
  21.                 html.row(id: book.key.id) {
  22.                     html.cell( book.sales )
  23.                     html.cell( book.title )
  24.                     html.cell( book.author )
  25.                     html.cell( book.price )
  26.                 }
  27.             }
  28.         }
  29.         break
  30.     case "edit":
  31.         log.info "edit: editing a book"
  32.         request.setAttribute 'id', params.id
  33.         forward '/WEB-INF/pages/edit.gtpl'
  34.         break
  35.     case "show":
  36.         log.info "show: getting book data"
  37.         def id = Long.parseLong(params.id )
  38.         Key key = KeyFactory.createKey("books", id)
  39.         def book = datastore.get(key)
  40.         response.setContentType("text/xml")
  41.         html.data {
  42.               author {
  43.                 mkp.yieldUnescaped("<![CDATA[" + book.author + "]]>")
  44.               }
  45.               price {
  46.                 mkp.yieldUnescaped("<![CDATA[" + book.price + "]]>")
  47.               }
  48.               sales {
  49.                 mkp.yieldUnescaped("<![CDATA[" + book.sales + "]]>")
  50.               }
  51.               title {
  52.                 mkp.yieldUnescaped("<![CDATA[" + book.title + "]]>")
  53.               }
  54.             }
  55.         break
  56.     default:
  57.         break
  58. }


  59. The data processor POST requests are routed to the Groovlet named processor.groovy, which handles the insert, update, delete operations, and persist changes to the entity. Gaelyk’s abstractions for the datastore make them quite straight forward to implement.


    war/WEB-INF/groovy/processor.groovy
    1. import com.google.appengine.api.datastore.Entity
    2. import com.google.appengine.api.datastore.Key
    3. import com.google.appengine.api.datastore.KeyFactory
    4. response.setContentType("text/xml")
    5. switch (params."!nativeeditor_status") {
    6.     case "inserted":
    7.         log.info "inserted: inserting a book"
    8.         def book  = new Entity("books")
    9.         book << params.subMap(['sales', 'title','author','price'])
    10.         book.save()
    11.         html.data {
    12.             action(type: "insert", sid: book.key.id, tid: book.key.id)
    13.         }
    14.         break
    15.     case "updated":
    16.         log.info "updated: updating a book"
    17.         def id = Long.parseLong( params.id ? params.id : params.gr_id )
    18.         Key key = KeyFactory.createKey("books", id)
    19.         def book = datastore.get(key)
    20.         book << params.subMap(['sales', 'title','author','price'])
    21.         book.save()
    22.         html.data {
    23.             action(type: "update", sid: book.key.id, tid: book.key.id)
    24.         }
    25.         break
    26.     case "deleted":
    27.         log.info "deleted: deleting a book"
    28.         def key = ['books', params.gr_id] as Key
    29.         key.delete()
    30.         html.data {
    31.             action(type: "delete", sid: params.gr_id, tid: params.gr_id)
    32.         }
    33.         break
    34.      default:
    35.         break
    36.  }




    Enjoy.



No comments:

Post a Comment