dhtmlXGrid Guide and Samples

Main features

  • wide and powerful client side api
  • navigation with keyboard
  • Dynamical loading
  • Data buffering
  • 90% compatibility with Scand's jTreeTable api (grid part)
  • fully customizable appearance
  • XML support
  • 12 predefined Cell Editors (eXcell)
  • ability to create your own Cell-Editors (eXcell)
  • three types of data sorting (date,string,int)
  • column resizing
  • horizontal & vertical scrolling
  • single/multi-line rows
  • single/multi row selection
  • on/off header
  • Supported browsers

  • IE 5.x and above
  • Mozilla 1.4 and above
  • FireFox 0.9 and above
  • Working with dhtmlXGrid

    Navigation with keyboard

    For keyboard navigation you can use following keys:
  • Tab - change to the next cell in row
  • Shift+Tab - change to the previous cell in row
  • Up, Down arrows - change to previous/next row
  • Enter - if in edit cell mode - close cell
  • Space - on checkbox or radiobutton - change state
  • F2 - edit cell
  • Esc - finish editing
  • Initialize object on page

    <link rel="STYLESHEET" type="text/css" href="../css/dhtmlXGrid.css"> <script src="../js/dhtmlXCommon.js"></script> <script src="../js/dhtmlXGrid.js"></script> <script src="../js/dhtmlXGridCell.js"></script> <div id="gridbox" style="width:200;height:200"></div> <script> mygrid = new dhtmlXGridObject('gridbox'); // or //mygrid = new dhtmlXGridObject(); //mygrid.attachToObject(document.body) mygrid.imgURL = "img/"; mygrid.setHeader("Column A, Column B"); mygrid.setInitWidths("100,250") mygrid.setColAlign("right,left") mygrid.setColTypes("ro,ed"); mygrid.setColSorting("int,str") mygrid.init(); mygrid.loadXML("grid.xml"); </script> Parameters passed to the constructor are:
  • object to attach grid to (should be loaded before calling constructor). If none, then you can use attachToObject method to attach grid to some parent.

  • Specify additional parameters of the grid:
  • imgURL - specifies the path to the folder with grid images
  • setHeader("Column A, Column B") - set column header labels
  • setInitWidths("100,150") - set column width in pixels
  • setColTypes("ro,ed") - set column types (with editor codes. See documentation for details)
  • setColAlign("right,left") - set column text align
  • setColSorting("int,str") - set column sorting type
  • loadXML("grid.xml") - load grid data from XML
  • Set Event Handlers

    <div id="treeBox" style="width:200;height:200"></div> <script> function doOnRowSelected(id){ ... } function doOnCellEdit(stage,rowId,cellInd){ if(stage==0){ ... return true; }else if(stage==1){ ... }else if(stage==2){ ... } } function doOnEnter(rowId,cellInd){ ... } function doOnEnter(rowId,cellInd){ ... } mygrid = new dhtmlXGridObject('gridbox'); ... mygrid.setOnRowSelectHandler(doOnRowSelected); mygrid.setOnEditCellHandler(doOnCellEdit); mygrid.setOnEnterPressedHandler(doOnEnter); mygrid.setOnCheckHandler(doOnCheck); ... mygrid.init(); mygrid.loadXML("../grid.xml"); </script> In most cases functions specified inside event handlers get some values with the arguments. For details about passed arguments please refer to API documentation.

    Adding nodes with Script

    <script> mygrid = new dhtmlXGridObject('gridbox'); ... mygrid.addRow(123,"text1,text2",1); mygrid.deleteRow(mygrid.getRowId(0)); </script> For details about passed arguments please refer to API documentation

    Loading data with XML

    <script> ... mygrid.setXMLAutoLoading("dynload.php");//to load additional data from server mygrid.init(); mygrid.loadXML("init.xml");//to load initial bloack of data from server </script> Parameters which go to url specified in setXMLAutoLoading:
  • rowsLoaded - number of rows in grid before request
  • lastid - last row id.
  • XML Syntax: <?xml version='1.0' encoding='iso-8859-1'?> <rows> <userdata name="NameOfGlobalUserDataBlock"></userdata> <row id="unique_rowid"> <userdata name="NameOfRowUserDataBlock"></userdata> <cell>cell content</cell> <cell>cell content</cell> </row> </rows>
    In PHP script use the following code for page header:
    <?php if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") ) { header("Content-type: application/xhtml+xml"); } else { header("Content-type: text/xml"); } echo("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"); ?>
    <rows> node is mandatory. It can contain grid related <userdata> blocks <row> can contain row related <userdata> blocks.


    To set userdata directly within XML use <userdata>
    It has just one parameter:
  • name

  • and value to specify userdata value

    Dynamical Loading while scrolling

    If your grid should contain large amount of rows (or you simply do not want to waist time loading hidden rows at startup), it would be better to load them while scrolling. For this purpose we made the grid to load rows dynamically using XML.
    See chapter "Loading data with XML" for xml structure and syntax of methods

    Buffering

    Buffering can be used to decrease the time for rendering the entire content of the grid at once (on startup). Instead just a part of available rows will be added to the document just from the beginning - other rows will be added while user scrolls the grid. To turn this feature off set the buffer size to 0. <script> mygrid = new dhtmlXGridObject('gridbox'); ... mygrid.enableBuffering(30);//30 rows will be rendered at once. mygrid.init() </script> If you use Dynamical Loading, then you can specify buffer size as secondparameter of setXMLAutoLoading method. By default it is set to 40 for Dynamical Loading.

    Manipulating rows

    A few examples of manipulating rows with grid API methods: <script> mygrid = new dhtmlXGridObject('gridbox'); ... var sID = mygrid.getSelectedId();//get id of selected row mygrid.cells(sID,1).setValue("New Value");//change value of second cell mygrid.setRowTextBold(sID);//set row test bold mygrid.moveRowDown(sID);//move selected row one position down var rInd = mygrid.getRowIndex(sID);//get index of selected row mygrid.setRowId(rInd,"100");//change id of selected row to 100 alert("This are : "+mygrid.getRowsNum()+" rows in the grid");//show alert with information about number of rows in the grid </script>

    Moving Rows

    To move Row programaticaly developer can use the folowing method: <script> mygrid.moveRowDown(rowId) mygrid.moveRowUp(rowId) </script>

    Smart XML Parsing

    The idea of Smart XML Parsing is simple - the entire tree structute loaded on client side, but only nodes which should be displayed are rendered. This helps to dramaticaly decrease loading time and general performance of large trees. Plus - in the contrary to Dynamical Loading - entrire tree structure is available for most of script methods (for example Search performed agains all nodes - not only rendered). To activate Smart XML Parsing use the following method: <script> tree.enableSmartXMLParsing(true);//false to disable </script> Smart XML Parsing do not work if tree loaded fully expanded.

    Checkboxes & Radiobuttons

    dhtmlxGrid supports both: checkboxes and radiobuttons. They are just types of columns you need to specify before initializtion. For more details see Use Cell Editors (eXcell) chapter <script> mygrid.setColTypes("ra,ch"); </script> You also can specify what value are considered as False for checkboxes and radiobuttons: <script> mygrid.raNoState = "No";//"No" will be "unchecked", all other values will be "checked" mygrid.chNoState = "0";//"0" will be "unchecked", all other values will be "checked" mygrid.init() </script>

    Increasing Performance

    Taking into account the general low performance of DHTML we introducrd two ways of increasing performance of large grids:
    1. Dynamical Loading
    2. Buffering
    3. Split the content of your grid into pages

    Multiline grid rows

    ...allows displaying grid rows in multiline mode (it is default state for Mozilla) or turn it of to have single-line rows (IE only). To enable multiline feature you need to do the following: mygrid.enableMultiline(true/false);

    Multiselection in Grid

    To enable multiselection mode you need to do the following: mygrid.enableMultiselect(true/false); Use [Shift/Ctrl] keys to select multiple rows at a time.

    Usage of Cell Editors (eXcell)

    There are some predefined cell editors delivered with dhtmlxGrid. They are:
  • ReadOnly (ro) - cell can't be edited
  • Simple Editor (ed) - text is edited inside cell
  • Text Editor (txt) - text is edited in popup multiline textarea
  • Checkbox (ch) - standard checkbox
  • Radiobutton (ra) - column oriented radiobutton
  • Select box (coro) - simple selectbox
  • Combobox (co) - select box with ability to add some other value
  • Image (img) - not editable. Value considered as url of image

  • Special types:
  • Color picker (cp) - simple color picker (just for example). Value considered as color code or name
  • Price oriented (price) - shows $ before value, all values eql 0 shown as na in red color
  • Dynamic of Sales (dyn) - shows up/down icon depending on value. Also color coding available (green/red)

  • To assign necessary types to columns use the following script method with comma delimmited list of editor codes: mygrid.setColTypes("ro,ed,txt,txt,ro,co");

    Define new Cell Editors (eXcell)

    Now we'll create new Cell Editor (eXcell) for dhtmlxGrid wich will edit values using simple text field and display strings aligned left, integers - aligned right:
    Complete way (not necessary to follow - just for understanding. Important if you want to incorporate some external editor f.e.)
    1. Choose the code for the new eXcell. In our case it is "test".
    2. Get eXcell template: function eXcell_test(cell){ try{ this.cell = cell; this.grid = this.cell.parentNode.grid; }catch(er){} /** * @desc: method called by grid to start editing */ this.edit = function(){ } /** * @desc: get real value of the cell */ this.getValue = function(){ return ""; } /** * @desc: set formated value to the cell */ this.setValue = function(val){ if(val.toString().trim()=="") val = "&nbsp;"; this.cell.innerHTML = val; } /** * @desc: this method called by grid to close editor */ this.detach = function(){ this.setValue(this.obj.value); return this.val!=this.getValue(); } } eXcell_test.prototype = new eXcell; 3. Add necessary code to this.edit() method. In particular it is creation of textfield inside grid cell and put there real (not formatted) value of the cell using this.getValue() method. this.edit = function(){ this.val = this.getValue(); this.obj = document.createElement("TEXTAREA"); this.obj.style.width = "100%"; this.obj.style.height = (this.cell.offsetHeight-4)+"px"; this.obj.style.border = "0px"; this.obj.style.margin = "0px"; this.obj.style.padding = "0px"; this.obj.style.overflow = "hidden"; this.obj.style.fontSize = "12px"; this.obj.style.fontFamily = "Arial"; this.obj.wrap = "soft"; this.obj.style.textAlign = this.cell.align; this.obj.onclick = function(e){(e||event).cancelBubble = true} this.obj.value = this.val this.cell.innerHTML = ""; this.cell.appendChild(this.obj); this.obj.focus() this.obj.focus() } 4. Now edit this.setValue(val) to format incomming value: this.setValue = function(val){ if(val.toString().trim()=="") val = "&nbsp;"; if(isNaN(Number(val))){ this.cell.align = "left"; }else{ this.cell.align = "right"; } this.cell.innerHTML = val; } 5. Now we are ready to edit this.getValue(). As we haven't added any additional elements to the cell content - the will be just one line of code inside: this.getValue = function(val){ return this.cell.innerHTML.toString(); } 6. Final step is to get rid of editor and fill cell with formated value in this.detach() method: this.detach = function(){ this.setValue(this.obj.value); return this.val!=this.getValue(); } 7. You can get the complete code here. Make sure your place your eXcell code after dhtmlxGridCell.js.

    Express way (make eXcell based on existing eXcell of common type)
    You can base your eXcell on one of existing eXcell - the choice depends on how the value should be edited. For example simple text field is enough for your needs, but you need some special formating. The do the following: 1. C hoose the code for the new eXcell. In our case it is "test" again.
    2. Template will be simplier and will be based on simple editor (code: ed). Some new code from the beginning, but then we skip this.edit() and this.detach() function eXcell_test(cell){ this.base = eXcell_ed; this.base(cell) this.getValue = function(){ return ""; } this.setValue = function(val){ } } eXcell_test.prototype = new eXcell_ed; 3. getValue and setValue you can get from points 4 and 5 above.

    Usage of eXcell
    Now you can use your new eXcell among other editors: mygrid.setColTypes("ed,ro,test");