Wednesday, March 27, 2013

jqGrid Learnings

I have been using jqGrid for a few projects that was done using PHP. For anyone who does not know what jqGrid is, its a fully featured library that allows you to display and manipulate your data in tabular form. Saves you tons of time writing pure tables to handle and manipulate your data. It has two variants where one is the commercialized version (jqSuite) and the free version is maintained here. The API is very much verbose with a plethora of methods for almost anything you would ever want to do in a grid. This post will be aimed at use cases to which i used jqGrid and what changes i needed to do in order to get it working.


  • Custom search on a button click
By default jqGrid sends a data search GET request on page load. It also has a refresh button in the bottom part. What i wanted was to send a GET request with the search parameters on a button click. To achieve this i first built the URL with the parameters as follows;


var length = jsPatientSearchCtrl.length;
var searchURL= "server.php?";
for(var i=0;i<length;i++){

 if($('#'+jsPatientSearchCtrl[i].id).val()!=''){

   searchURL+="&";
  
   searchURL+=jsPatientSearchCtrl[i].desc+"="+$('#'+jsPatientSearchCtrl[i].id).val();
   
 }
}
Here i am iterating through the JSON array i have defined to hold the data objects within my given page. After creating the URL with the parameters you have to tell jqGrid to reload the data as follows;

jQuery("#list2").jqGrid('setGridParam',{url:searchURL}).trigger("reloadGrid")

This will send another GET request to the server to reload the Grid with new data according to our changed search criteria when the user clicks on the search button.


  • Editing grid data using a form submission
By default jQGrid provides the ability to edit the fields within our Grid by opening a dialog where by you can change the details for a given record and submit it. To do this, first you have to enable the edit option in your grid. You do this as follows;


jQuery("#list2").jqGrid('navGrid',
'#pager2',
{edit:true,add:false,del:true,search:false}
); 
Here i have enabled the edit option by setting the value to true and have disabled the add and search functionality as this was not required in my scenario. After that you need to define which columns you want to edit. You do this within your colModel parameter which you give when constructing your jqGrid. I present what i have used;


colModel:[ 
  {name:'Ref',index:'id', width:55,sortable:false,editable:false,editoptions:{readonly:true,size:10}},
  {name:'Identity',index:'patient_identity', width:90,sortable:false,editable:true,editoptions:{size:10}}, 
  {name:'Reference',index:'patient_identity', width:90,sortable:false,editable:true,editoptions:{size:10}}, 
  {name:'Date',index:'date', width:90,sortable:false,editable:true, editoptions:{size:10}}, 
  {name:'Time',index:'time', width:50,sortable:false,editable:true, editoptions:{rows:"1",cols:"10"}}, 
  {name:'Name',index:'patient_name', width:130,sortable:false,editable:true,edittype:"textarea", editoptions:{rows:"1",cols:"20"}}, 
  {name:'Referred',index:'referred_by', width:100,sortable:false,editable:true,edittype:"textarea", editoptions:{rows:"1",cols:"20"}}, 
  {name:'Blood',index:'blood_collected_at', width:120, align:"right",sortable:false,editable:true,edittype:"textarea", editoptions:{rows:"1",cols:"20"}}]
Important things to note here is that certain fields we have set editable:false which signifies that these values will not be able to be changed by the user when editing. To enable editing on a particular column we define it as editable:true. Optionally you can define a size. You do this using the editoptions attribute. For example as per the above code snippet, we have used editoptions:{size:10}  to give a size of 10 to that particular text field.

If you want to define a text area, this can also be achieved. Again revisiting the above code, we have done this using editiontype:"textarea",editoptions:{rows:"1",cols"20"}. There are many other types you can define such as check boxes etc. More info on the supported types in the edit option can be found here.


  • Close the Add/Edit dialogs upon submit
By default the Add/Edit dialogs do not close after submitting the values. You have to press the close button yourself. It was required for me to close the dialog on submit. This was achieved as follows;


jQuery("#list2").jqGrid('navGrid',
'#pager2',
{edit:true,add:true,del:true,search:false}
,{width:500,closeAfterEdit: true},{width:500,closeAfterAdd:true}); 

As you can see within the code snippet, i have set the attribute closeAfterAdd  and closeAfterEdit  as true. This will close the Add/Edit dialog when the user clicks on the submit button.

Another thing to note here is that when you enable editing and adding, you need to specify to which URL the POST parameters on submit should be sent to. You do this as follows;


jQuery("#list2").jqGrid({
editurl: "editperson.php"
  });

Note that the data for add, edit and delete are sent to the same URL, so you need to identify the operation uniquely. jqGrid by default sets a parameter for us to distinguish this when sending the POST request to the URL we prodive in the editurl attribute. With PHP this is how we handle it;


 if(isset($_POST["oper"])){
 $operation = $_POST["oper"];
 
 switch($operation){
 case "del":
 break;
 
 case "add":
 break;
 
 case "edit":
 break;
 }
}

As you can see jqGrid by default sets a parameter named oper which defines which operation the data that is sent belongs to. So we can handle our logic according to whether its an add/edit or delete.

That is about it on use cases i have come across when using jqGrid. Some of the problems i faced were solved after some Google searching and putting together information gathered from various sources. Hence the purpose of this post was to put it altogether and provide a one-stop point for most of the common scenarios you might use jqGrid for.

Thank you for reading. Have a great day ahead.

Monday, March 25, 2013

Drupal to the rescue

My sister wanted to jump start her business in migration services related to Sri Lanka and wanted a website done. Contemplating on how to approach this within the time frame requested i was thinking along a few dimensions.


  1. The site should be built in 1-2 days time
  2. Must be cost effective to host and manage
  3. Ability for my sister to manage the content as time goes by
  4. Deliver with minimal effort
First i thought i would mash up a site coding it myself. As the cost effective (the elegant way of say cheap) way of hosing as i know is with PHP i wanted to initially do the coding myself. As i am primarily from a Java background and given my PHP skills were a bit rusty since the only time i really code in PHP is when i do freelancing related projects, i was thinking whether i could finish it on the given timeline.

This is when i thought in the line of CMSs (Content Management Systems). There are many options to chose from such as Drupal, Wordpress, Joomla. Wordpress byitself is not a fully fledged CMS per se, but it gives you the ability to administer and manage your content.I went ahead with Drupal mainly because i found an ebook that explained it in detail and i was able to figure it out within a couple of hours time. Im not saying the other two options are less competent, but in the end i believe you have to approach the solution with something you are comfortable with given the time frame and since this is not like a mission critical system i am aiming to develop there were no explicity trade-offs.

Drupal with its modular architecture made me feel at home since its concept is easily comprehensible. Also its intuitive administrative console allowed me to teach my sister how to manage the site in the future without my help since she would want to change the content as time goes on.

The main important elements with regards to Drupal was;

  • Regions
          Region is all about page layout in its simplest terms. If you are to hand code with html and css, you will probably use div elements to divide your page for instance to hold the header part, footer section, and main content section. With Drupal you have a multitude of themes to chose from. I would say first design your website deciding on how you want your elements to be aligned. I use Adobe Fireworks for my initial design purposes. Then depending on your page layout you need to select the Drupal theme that best fits your layout since all themes have a specific layout to place content.

  • Blocks
         A block is a particular element in which you group a set of content that you want to display. It can be a navigation menu, or you can even build your own custom block which would consist of a certain section you want to present. Also blocks give you the ability to be able to be displayed only in certain pages which i believe is such a great feature to give the flexibility to the user.

  • Content Types
         There are mainly two content types when you first start out. Stories and Pages. A Story typical is published on the home page and allows the users to comment. It is recommended to use this for news feed and content that is updated regularly. Pages are static content which is mostly what is required when building web pages. You can even stick it on the front page if required so it can act like a story in someway. The beauty of Drupal is that you can even define your own content types to match your requirements. With Views and CCK (Content Construction Kit), you can customize Drupal according to your needs.

This is the site i built for my sister in the end. Its not flashy or anything, but hey this is the best i could achieve with around 6 hours of work to get it up and running. I used the basic bartik theme that comes by default since i did not see the need to adapt any other. You can also change the look and field by injecting your own customer CSS file. That is another topic by itself.

CMSs save alot of time you would spend aligning your content and adapting and incorporating possible changes in the future. It allows you to manage your content, security and users with ease. Also it prevents your site from known attacks such as cross side scripting, sql injections etc which otherwise you would be handling by yourself or through a framework you would be using. Though it is not as exciting as hand coding yourself, for me, it was the right tool for the job in this given situation. After all you should work smart and not hard right ;)

Cheers all and thank you for reading. As always comments and criticisms are always welcome.