Dojo Enhanced Grid with Checkbox like radio button exmaple


There are some situations where we need to show Grid with Check box but should perform as Radio button.

Below code snippet is an example of extended Dojo Enhanced Grid which shows Check-box but works as Radio button.

Prerequisite :
// 1. Dojo
// 2. Add required dojo components like dojox/grid/EnhancedGrid used in required section.
// 3. Include Enhanced grid css on jsp. Get it from dojo site.


1. JSP HTML code snippet.

   <!-- Enhanced grid data placeholder -->
<div id="gridData">
<div id="gridDataCP" data-dojo-type="dijit/layout/ContentPane"></div>
</div>

2. JavaScript code snippet.

/*************************************************************************
 * Dojo Enhanced Grid implementation with checkbox,
 * but achieved functionalites like single select radio button.
 **************************************************************************/


/**
 * Enhanced grid implementation using sample data.
 * gridData is a collection of data needs to be displayed.
 */
function createEnhancedGridList(gridData, noDataMsg) {

require(["dojox/grid/EnhancedGrid", "dojo/data/ItemFileWriteStore","dojox/grid/enhanced/plugins/IndirectSelection" ],
function(EnhancedGrid, ItemFileWriteStore, IndirectSelection){

if(noDataMsg == null){
noDataMsg = "";
}

deleteElement("grid");

var data_list = getGridList(gridData);
console.log("Set up data store.");
/*set up data store*/
   var data = { identifier: 'id', items: [] };
 
   var rows = 0;
if(data_list != null && data_list.length >0 ){
rows = data_list.length;
}
console.log("rows =" + rows);

console.log("set data item.");
   for(var i=0, l=data_list.length; i<rows; i++){
     data.items.push(dojo.mixin({ id: i+1 }, data_list[i%l]));
   }
 
   console.log("create store.");
   var store = new ItemFileWriteStore({data: data});

   console.log("create layout.");
   /*set up layout*/
   var layout = [[
     {'name': 'User', 'field': 'user', 'width': '20%', noresize: true},
     {'name': 'Phone', 'field': 'phone', 'width': '20%', noresize: true}
   ]];

   //If sorting required for specific column.
  // function canSort(col) { return Math.abs(col) === 2; }
 
   console.log("Create Grid");
 
   /*create a new grid:*/
   var grid = new EnhancedGrid({
    canSort: function(colIndex) {
           if ((colIndex == 2) || (colIndex == 3) || (colIndex == 5)) {
               return false;
           }
           return true;
       },
       id: 'grid',
       style: "width:100%;",
       store: store,
       structure: layout,
       rowSelector: '0px',
       rowsPerPage : rows,
       noDataMessage : noDataMsg,
       escapeHTMLInData: false,    
       plugins: {indirectSelection: {headerSelector:false, width:"20px", styles:"text-align: center;", pagination:{pageStepper:false}}  }},  // adds checkbox to select that row
       document.createElement('div'));
 
   console.log("Set into node.");
   /*append the new grid to the node*/
   dojo.byId("gridDataCP").appendChild(grid.domNode);
 
   console.log("Start up Grid.");
   /*Call startup() to render the grid*/
   grid.startup();
   grid.resize();
 
   //row selection event handling
   dojo.connect(grid, "onSelected",  processSelectedRow);
   dojo.connect(grid, "onDeselected",  processDeselectRow);

});

 
}





/**
 * Handles selected row event.
 * @param rowIndex
 */
function processSelectedRow(rowIndex){
console.log("rowIndex =" + rowIndex);

if(rowIndex <0){
console.log("invalid : rowIndex =" + rowIndex);
return false;
}

var gridNode = null;
if(dijit.byId("grid") != null){
gridNode = dijit.byId("grid");
}

if(gridNode == null){
console.log("invalid : grid");
return false;
}

var userId = null;

if(gridNode != null){
// Get all selected items from the Grid:
   var items =  gridNode.selection.getSelected();
   var rowCount = gridNode.rowCount;

   for(var i=0; i<rowCount; i++){
    if(i!=rowIndex){
    gridNode.rowSelectCell.toggleRow(i,false);
    }
   }
 
   if(items.length){
       // Iterate through the list of selected items.
       // The current item is available in the variable
       // "selectedItem" within the following function:
       dojo.forEach(items, function(selectedItem){
           if(selectedItem !== null){
               // Iterate through the list of attributes of each item.
               // The current attribute is available in the variable
               // "attribute" within the following function:
               dojo.forEach(gridNode.store.getAttributes(selectedItem), function(attribute){
                   // Get the value of the current attribute:
                   var value = gridNode.store.getValues(selectedItem, attribute);
                   //break statement is not part of dojo.forEach.
                   //console.log("selectedItem =" + selectedItem + ", attribute =" + attribute);
                 
                   //console.log("value =" + value );
                 
                   if(attribute == "id"){
                    //console.log("value  =" + value );
                    userId = value;
                   }
               });
           }
       });
   }
     
}else{
console.log("No such grid node found. Unable to get selected Grid row data.");
}

console.log("resizing grid.");
gridNode.resize();

console.log("userId = " + userId);
//Handle selected row event by userId. For Ex. populateSelectedUserData(userId);

}



/**
 * Processes Un-check checkbox event.
 * @param rowIndex
 */
function processDeselectRow(rowIndex){
console.log("rowIndex =" + rowIndex);

require(["dojox/grid/EnhancedGrid", "dojo/data/ItemFileWriteStore","dojox/grid/enhanced/plugins/IndirectSelection" ],
function(EnhancedGrid, ItemFileWriteStore, IndirectSelection){

//Handle uncheck event here. For example : clear displayed date etc.

});
}




/**************************************************
 * Utility functions.
 **************************************************/


/**
 * This function recursively destroys all items for the given dijit node.
 */
function deleteElement(nodeId){
console.log("nodeId =" + nodeId);
if(nodeId != null && nodeId != ""){
require(["dijit/registry"], function(registry) {
if(registry.byId(nodeId)!= null){
registry.byId(nodeId).destroyRecursive();

if(registry.byId(nodeId)!= null){
registry.byId(nodeId).destroy();
}

if(registry.byId(nodeId) == null){
console.log(nodeId + " dijit object destroyed from registry.");
}
}
});

if(dijit.byId(nodeId) != null){
dijit.byId(nodeId).destroy();
}

require(["dojo/dom-construct"], function(domConstruct){
if(dojo.byId(nodeId) != null){
domConstruct.destroy(nodeId);
console.log(nodeId + " dom object destroyed.");
}
});
}else{
console.log("Invalid nodeId.");
}
}





/**
 * Returns Grid column data. Set all required data for grid.
 * @param gridItems
 * @returns {Array}
 */
function getGridList(gridItems){

var gridDataList = new Array();
if(gridItems != null && gridItems.length > 0){
var rows = gridItems.length;
if(rows > 0){
for(var i=0; i<rows; i++){
var rowData = new Object();
var userId = gridItems[i].userId;

rowData.id = userId;
rowData.user = "";
rowData.phone = "";

//1. user
if(gridItems[i].user != null){
rowData.user = gridItems[i].user;
}
//2. phone
if(gridItems[i].phone != null){
rowData.phone = gridItems[i].phone;
}

gridDataList[i] = rowData;
}
}
}

return gridDataList;
}




Comments

Popular posts from this blog

SVN plugin setup in IBM RAD8 - Checkout project from SVN

How to Upgrade Dojo in IBM WebSphere Portal v8.0