Grails, jQuery & the jQuery Grid - Part One

dave

Administrator
Staff member
I've been intending for quite some time to write a series of articles on my experiences so far with Grails based web applications. So I'm tackling this now whilst my experiences are still relatively fresh before my focus takes another direction.

I don't want to go into the why's of using grails when there are already many other frameworks out there but for me, I love Java for its power, vast number of libraries and community support available. I also love Ruby On Rails, for its convention over configuration benefits so when I discovered Grails is a kind of merge of the two, it quickly gained my interest. There are many cool features to Grails but to pinpoint a couple, not having to go through all the initial setting up of Spring, Hibernate, JPA etc is a real time saver, and how it allows you to use it's own Groovy code alongside pure Java is something in my opinion both very clever and incredible beneficial to us web developers.

My target for these tutorials are not just for beginners to Grails but for anyone looking for quick how-to instructions to use Grails with various Ajax features such as displaying data in a jQuery grid, ajax filtering of data.

I do make the assumption however that you already know the basics of a grails based application and can already create, modify and deploy projects. I also don't want to insist on any particular IDE for working on these tutorials, although I will be using IntelliJ's IDEA IDE, Netbeans also has great Grails support but at the time of writing does not offer gsp tag completion. I cannot offer any other comment on the others as I am not familiar with Grails support in the other main contenders.

I also cannot recommend enough the combination of using Firefox as your browser with the Firebug plugin installed so you can keep an eye of your AJAX calls from your page to server. Firebug is a great tool that allows you to easily see what you are sending and what you are receiving.

Anyway enough introduction, let's move onto the first tutorial of my series.

Grails, JQuery and the Jquery Grid.

In this tutorial I aim to show you how to use the jQuery Grid to present data to your users.

I am using Grails version 1.2 alongside MySQL database.

I will setup a mock up of a customer database for this example, so first you will need to create a new Grails project and setup your datasource details so you are all setup ready to go.

The first step after you've created your project and defined your datasource is to create a new Grails Domain class called Customer. I've kept it simple, but with enough fields for us to create and display several columns in a grid.

Code:
class Customer {
    static constraints = {
    firstName(blank:false,maxSize:50)
    lastName(blank:false,maxSize:50)
    age(nullable:true)
    emailAddress(nullable:true)
  }

  String firstName
  String lastName
  Integer age
  String emailAddress
}
Once your class is defined, you should go ahead and generate the customer controller and corresponding views.

Now would be a good time to add some test data so we have something we can use to manipulate our views. A handy shortcut to create test data here is to edit the bootstrap groovy file so we can create some data at the time our application is launched. This is a technique I often use to preload testdata.

Code:
class BootStrap {

  def init = { servletContext ->
    // if we have an empty customer database,
    // create some test data
    if (Customer.count() == 0) {
      new Customer(
        firstName:'John', lastName:'Smith',
        age:27,
        emailAddress:'john@somewhere.com'
      ).save()

      new Customer(
        firstName:'Frank', lastName:'Malone',
        age:37,
        emailAddress:'frank@somewhere.com'
      ).save()

      new Customer(
        firstName:'Dave', lastName:'Brown',
        age:34,
        emailAddress:'dave@somewhere.com'
      ).save()

      new Customer(
        firstName:'Barney', lastName:'Rubble',
        age:44,
        emailAddress:'barney@somewhere.com'
      ).save()
    }
  }

  def destroy = { }
  }
}
I will also change the urlmappings so when we launch the application our default page is the customer index view :

Code:
class UrlMappings {
  static mappings = {
    "/$controller/$action?/$id?"{
      constraints {
        // apply constraints here
      }
     }
    "/"(controller:"customer",action:"index")
    "500"(view:'/error')
  }
}
So try running the application now and you should see the default presented list on the customer page. So far so good.

Before we create the necessary adjustments to use a jQuery grid, you will first need to download the required javascript librarys as well css styles for your grid from the following links:

jQuery latest release

jQuery Grid latest release - contains the necessary javascript and css (ui.grid.css). Copy the ui.grid.css to the web-app/css folder.

jQuery UI css themes : theme download - this is a great site that allows you to visual different UI themes for jquery widgets/plugins before downloading the necessary css/images.

I download the 'min' versions of the javascript librarys to cut down download time for the user. jquery.jqGrid.min.js and jquery-1.3.2.min.js both go into the web-app/js folder.
You theme will be downloaded as a zip file, you will need to copy the jquery-ui-1.7.2.custom.min.js script into your applications js folder and the contents of the css folder go into your web-app/css folder. For the purpose of this tutorial I downloaded the ui-lightness theme.

So now I want to switch from the default list view, to a jQuery Grid to present our customer data.

Edit your Customer/list.gsp, and perform the following.

1. Include our new javascript librarys by adding the includes into the head section. Our css style sheet should also be reference by also adding to the head section. Your head section should then contain the following:

Code:
<link rel="stylesheet" href="${resource(dir:'css',file:'main.css')}" />
<link rel="stylesheet" href="${resource(dir:'css',file:'ui.jqgrid.css')}" />
<link rel="stylesheet" href="${resource(dir:'css/ui-lightness',file:'jquery-ui-1.7.2.custom.css')}" />
<g:javascript library="jquery-1.3.2.min"/>
<g:javascript library="jquery-ui-1.7.2.custom.min"/>
<g:javascript library="grid.locale-en"/>
<g:javascript library="jquery.jqGrid.min"/>
2. Remove the tag and contents of
tag as well as the paginator tag that immediately follows it.3. I usually create page fragments for my jquery specific grids but for this example we will just place the code directly into the main list page.

You have to create a table element to hold our grid, as well as div element to go at the end of the table to display record count, paginator.

Insert the following jquery Grid definition. This defines a very basic grid which will be rendered when the page loads in the browser. Notice the url parameter, url:'jq_customer_list'. This is the url from which the grid will load its data. I have also specified the format of the data will be JSON. These parameters lead us to our next stage, we need to create the necessary function in our Customer controller that will return the data.

Code:
<!-- table tag will hold our grid -->
<table id="customer_list" class="scroll jqTable" cellpadding="0" cellspacing="0"></table>
<!-- pager will hold our paginator -->
<div id="customer_list_pager" class="scroll" style="text-align:center;"></div>

<script type="text/javascript">// <![CDATA[
  /* when the page has finished loading.. execute the follow */
  $(document).ready(function () {
    jQuery("#customer_list").jqGrid({
      url:'jq_customer_list',
      datatype: "json",
      colNames:['First Name','Last Name','Age','Email Address','id'],
      colModel:[
        {name:'firstName'},
        {name:'lastName'},
        {name:'age'},
        {name:'email'},
        {name:'id'}
     ],
    pager: jQuery('#customer_list_pager'),
    viewrecords: true,
    gridview: true
    });
  });
// ]]></script>
4. Create the jq_customer_list action in the Customer controller to respond to the grids request for JSON data.

As we are returning JSON type data, you must add an import to the top of the controller : import grails.converters.JSON

Note that the order of the fields must match the order in which we defined the order in the colModel and colNames in the grid definition. The minimal code to return the data is as follows:

Code:
def jq_customer_list = {
  def customers = Customer.list()
  def jsonCells = customers.collect {
    [cell: [it.firstName,
    it.lastName,
    it.age,
    it.emailAddress], id: it.id]
  }
  def jsonData= [rows: jsonCells]
  render jsonData as JSON
}
5. Try and run your application, if all succeeded you should be presented with your customer data in a nice looking grid.

View attachment 1

The entire project for this tutorial can be downloaded in the attachments to this post.

In my next tutorial I will take what we have done so far, and implement ajax pagination and table sorting when the user clicks on a column header.
 

plivak

New member
Newbie Question - generation of these views?

"Once your class is defined, you should go ahead and generate the customer controller and corresponding views."

Sorry to bother you with such a basic question, but if you aren't using scaffolding in this example, did you roll your own "corresponding views" or is there something else in grails that enables you to auto-generate those?

Thanks!
 
A

Amit Sirohiya

Guest
the only library used with grails 2.3.0 is jquery.


want this code in grails 2.3.0 coz cant access jqGrid......

help would be appreciated

thnks.
 
inciclesolmeno thingiverse.comWindows 7 Product Id Key 00371 OEM 8992671 00524 Of Product Key Activation 6l https://cdn.thingiverse.com/assets/70/b0/60/1d/02/gambar_gadis_tudung_bogel.html L'alba Separa Dalla Luce L'ombra.pdf https://cdn.thingiverse.com/assets/70/b0/60/1d/02/gambar_gadis_tudung_bogel.html AffolmeftoM thingiverse advarmaDiamezet Download Solucionario De Transferencia De Calor, Holman 8 Edicion - Download DMG Audio – All Plugins Bundle 2019.6.29 VST, VST3, RTAS, AAX x86 x64 thingiverse.com stoovadexmalashoonna thingiverseenactEcotsindusa thingiverse.com ThemPripsgymnereme Download
 
inciclesolmeno Wtm Copy Protection Crack Serial KeygenSafenet Sentinel Dongle Crack Software - thingiverse HD Online Player (astro boy 1080p kickass torrents) thingiverse.com AffolmeftoM https://cdn.thingiverse.com/assets/74/4d/cc/26/c5/chadrcari802.html advarmaDiamezet thingiverse.com EravyBroowlybrell Download HyloalpSlopleRaign Download thecroods2moviedownloadinhindi DownloadenactEcotsindusa https://cdn.thingiverse.com/assets/74/4d/cc/26/c5/chadrcari802.html ThemPripsgymnereme thingiverse
 
Scanmaster-elm 2.1 Keygen Download Accelerator thingiverse.comThe.Message.1976.[Dual-Audio][Hindi-Eng]DVDRip.720p.AC3.Riyaz-ul~RKH.avi Download InfatryCargoPorgeGon thingiverse Wondershare MobileTrans 7.9.12 Crack Registration Code [2019] Cyberlink PowerDirector Ultimate v12.0.2726 Patch REiS Serial Key keygen advarmaDiamezet thingiverse EravyBroowlybrell thingiverse.com HyloalpSlopleRaign Download HD Online Player (Toilet - Ek Prem Katha movie hd down) https://cdn.thingiverse.com/assets/35/85/0b/b9/20/PizzaConnection3activationcodeandserialnumber.htmlenactEcotsindusa Download Embarcadero Rad Studio Xe8 Serial Number HD Online Player (Catwalk Poison 127 (CWPBD 127) Risa )
 
inciclesolmeno DownloadHD Online Player (Gadar Ek Prem Katha 2001 Hindi Movie) thingiverse.com InfatryCargoPorgeGon https://cdn.thingiverse.com/assets/99/d9/e3/5d/17/yanntorch364.html AffolmeftoM thingiverse advarmaDiamezet Fireplace Full Hd 1080p Downloadsl Rob Papen Plugins Pack - R2R [deepstatus] Download Accusonus ERA Bundle Pro 4.1.0 Keygen Junnark WinFormsGen 1.0.0.2 Professional Plus Download rlg mgsone drivers https://cdn.thingiverse.com/assets/99/d9/e3/5d/17/yanntorch364.htmlDvdReMakePro V3.5.3 cracked.rar Download Pc https://cdn.thingiverse.com/assets/99/d9/e3/5d/17/yanntorch364.html ThemPripsgymnereme thingiverse.com
 
Safe365 SD Card Data Recovery Wizard 8.8.9.1 Serial Key Downloaducancam v9 dongle crack 11 3.3.5 wow mr fish 17 Igor Pro Mac Download Crack Internet Download AffolmeftoM thingiverse advarmaDiamezet https://cdn.thingiverse.com/assets/e2/fc/d8/44/dd/Xclubwrestlingepisode21.html EravyBroowlybrell thingiverse HyloalpSlopleRaign thingiverse stoovadexmalashoonna https://cdn.thingiverse.com/assets/e2/fc/d8/44/dd/Xclubwrestlingepisode21.htmlenactEcotsindusa mm4xpriceactionsoftwaredownload ROBLOX RUMBLE QUEST HACK SCRIPT 2020 COINS LEVELS MAC OS WIN MacOSX thingiverse
 
klawiatura titanum tk101 usb sterowniki download Downloadserial number for adobe premiere pro cc 2014 thingiverse InfatryCargoPorgeGon thingiverse.com AffolmeftoM Download advarmaDiamezet thingiverse EravyBroowlybrell AutoCAD LT 2015 xforce keygen 64 bit HyloalpSlopleRaign thingiverse.com stoovadexmalashoonna https://cdn.thingiverse.com/assets/ab/dc/a3/2b/96/ff_dax_font_familyrar.htmlMappoint 2013 Crack the reader movie download 720p 11 Reallusion Cartoon Animator 4.1 Crack Full Torrent 2020 thingiverse.com
 
OCAD 10.3.0.957 Professional Multi thingiverse3000 Dias No Bunker Pdf Download thingiverse InfatryCargoPorgeGon Rurouni.Kenshin.2012.BluRay.720p.DD5.1.x264-YYeTs.mkv win timer tester 1.1 download https://cdn.thingiverse.com/assets/f6/50/41/67/47/Pes_2013_dt11img.html Sanatoasa Supla Satula Pdf Download 1 Download Linkrunner At 2000 Software Download HD Online Player (telugu 5.1 dvd movies free download) Free Download Games Hidden Object Full Unlimited Version https://cdn.thingiverse.com/assets/f6/50/41/67/47/Pes_2013_dt11img.html stoovadexmalashoonna https://cdn.thingiverse.com/assets/f6/50/41/67/47/Pes_2013_dt11img.htmlAdobe Acrobat XI Pro 11.0.3 Multilanguage [ChingLiu] download thingiverse.com ThemPripsgymnereme thingiverse
 
Midtown Madness 3 Free Download Full Version For Pc Opto Coupler A1458Goavydrombdriergo Far Cry 3 Mod Ziggys Mod 30 Crack InfatryCargoPorgeGon Skyglobe Download For Windows 7 Direct Dil Se Tamil Dubbed Movie Torrent Download advarmaDiamezet Download 8 Ci Sinif Fizika Test Suallarinin Cavablari Download Digital Music Mentor 2.6.0.5 Download Fzdhtjw--Gb1-0 Font https://cdn.thingiverse.com/assets/a5/09/52/9a/62/dakojosc33.htmlAutodata 3.38 Install Windows 7 32bit thingiverse.com ThemPripsgymnereme Malwarebytes Anti-Malware Premium 2.1.8.1057 Keymaker Serials setup free
 
inciclesolmeno thingiverse.comenglish to marathi grammar pdf free download thingiverse Realtime Landscaping Architect Crack Latest Serial Key [2020] https://cdn.thingiverse.com/assets/f0/82/2b/44/99/irandam_ulagam_movie_hd_download.html AffolmeftoM oxford advanced learner's dictionary apk cracked CompleteBusinessStatisticsAczelpdf Download EravyBroowlybrell Download HyloalpSlopleRaign watchonlinestarplusserialhatim stoovadexmalashoonna DownloadARK Survival Evolved v238.3 x64 crack LumaEmu thingiverse Chamatkar Chintamani English Pdf Free 12 D16 Group Drumazon VSTi V1 4 0 Incl Keygen AiR.rar - 21
 
Top