Creating a Rico LiveGrid

Rico LiveGrid displays data in a scrolling table, with the data buffered in a 2-dimensional JavaScript array. As the user scrolls vertically through the grid, data is dynamically copied from the array onto the grid. The buffer can can be loaded from:

  1. a javascript array
  2. an HTML table
  3. an XML file
  4. a SQL database query
  5. a custom javascript callback function

Usage Model 1: Loading data from a javascript array

Usage Model 2: Loading data from an HTML table

Usage Model 3: Loading data from an XML file

Usage Model 4: Loading data from an SQL database query

The descriptions below apply directly to the ASP and PHP implementations of the Rico LiveGrid plug-ins. The concepts are the same in .net, but the implementation is quite different (examine ex2simple.aspx to see how this gets implemented in .net).

Usage Model 5: Loading data using a custom callback function

This model works the same way as models 3 and 4 except that, rather than fetching data using an xmlHTTPrequest, the data is fetched using javascript callback functions. This allows you to do creative things in the callback function - like call Google Gears. Setting up the callback is very easy. Rather than passing a string containing the data provider's URL to the AjaxXML or AjaxSQL constructor, you just pass the callback function instead.

The code that follows is taken from examples/client/gridJSbuffer.html, which uses the AjaxXML buffer. The "jsfetch" callback function returns a 2-dimensional array that is 100 rows long by 5 columns wide. Note that AjaxXML only loads its buffer once (at grid startup), so jsfetch will only be called once. The options hash is identical in structure to the options hash used by Prototype's Ajax.Request method.

buffer=new Rico.Buffer.AjaxXML(jsfetch);

function jsfetch(options) {
  Rico.writeDebugMsg("jsfetch");
  var newRows=[], offset=options.parameters.offset;
  for (var r=0; r<100; r++) {
    var row=[];
    row.push(offset.toString());
    row.push(new Date().toString());
    for (var c=2; c<5; c++) row.push('cell '+r+':'+c);
    newRows.push(row);
  }
  options.onComplete(newRows);
}

The code that follows is taken from examples/client/gridJSbuffer2.html, which uses the AjaxSQL buffer. The "jsfetch" callback function simulates a 2-dimensional array that is 500 rows long by 5 columns wide. However, only a section of that array is returned during any one callback -- just the rows from options.parameters.offset to options.parameters.offset + options.parameters.page_size.

buffer=new Rico.Buffer.AjaxSQL(jsfetch);

function jsfetch(options) {
  var newRows=[], totrows=500;
  var offset=options.parameters.offset;
  var limit=Math.min(totrows-offset,options.parameters.page_size)
  for (var r=0; r<limit; r++) {
    var row=[];
    row.push(new Date().toString());
    row.push(offset.toString());
    for (var c=2; c<5; c++) row.push('cell '+(r+offset)+':'+c);
    newRows.push(row);
  }
  options.onComplete(newRows,false,totrows);
}

options.onComplete takes the following parameters:

Debugging

Rico 2.0 includes the ability to route time-stamped debug messages to a message log. The log may be an html textarea or the browser's javascript console.

LiveGrid is programmed to send a number of messages to the message log that may prove helpful in debugging. You can also send your own messages by using Rico.writeDebugMsg(). For example:

Rico.writeDebugMsg('My debug message');

Grid Menus

Rico LiveGrids come with a lot of functionality built in. To access that functionality, Rico includes a default set of menus -- defined in ricoLiveGridMenu.js. To use the default menu, simply load the 'LiveGridMenu' module and then assign the grid's menu property to an instance of the Rico.GridMenu class.

  Rico.loadModule('LiveGridMenu');
  ...
  var ex1=new Rico.LiveGrid ('ex1', buffer, grid_options);
  ex1.menu=new Rico.GridMenu();

By default, the menu will open when a user double-clicks on a grid cell. To change the event that opens the menu, assign a value to the grid's menuEvent option. The following code will open the menu on a right-click:

  Rico.loadModule('LiveGridMenu');
  ...
  var grid_options = {
    menuEvent: 'contextmenu'
  }
  var ex1=new Rico.LiveGrid ('ex1', buffer, grid_options);
  ex1.menu=new Rico.GridMenu();

Rico.GridMenu provides a callback (dataMenuHandler) so that additional menu items can be added. The grid menu is always built dynamically -- customized to the row and column the user has clicked on. So the callback function is called every time the menu is invoked and must add the desired menu items at each invocation.

  Rico.loadModule('LiveGridMenu');
  ...
  var ex1=new Rico.LiveGrid ('ex1', buffer, grid_options);
  ex1.menu=new Rico.GridMenu();
  ex1.menu.options.dataMenuHandler=myCustomMenuItems;
  ...
function myCustomMenuItems(grid,r,c,onBlankRow) {
  if (buffer.getWindowValue(r,c)=='Special Value')
    grid.menu.addMenuItem("Special menu item", specialAction);
}
function specialAction() {
  ...
}

It is also possible to create completely custom menus. For an example, see ex5.php/asp/aspx.

Notes

Reference

Constructor


  var grid = new Rico.LiveGrid (table_id, rico_buffer, grid_options);

Options

Grid Size

visibleRows (rows in .net plug-in)
How many rows of the grid are made visible? A positive integer specifies that the grid should always contain exactly that many rows.

Negative values have the following meanings:

String values have the following meanings:

minPageRows
Minimum # of visible rows. Used only when visibleRows < 0. (default: 2 - after Rico 2b3, 1 - up to Rico 2b3)
maxPageRows
Maximum # of visible rows. Used only when visibleRows < 0. (default: 50)
defaultWidth
An integer used in setting the initial width of columns. See the column width option for an explanation. (default: -1 if initializing from an HTML table, 100 otherwise)
scrollBarWidth
For some calculations, LiveGrid needs to know the width of scrollbars on the page. (default: 19)
minScrollWidth
Minimum scroll area width in pixels when width of frozen columns exceeds window width. (default: 100)

Grid Data

offset
First row of data to be displayed (default: 0)
prefetchBuffer
Load the buffer (and therefore the grid) on page load? (default: true)
sortCol
Name or index of column for initial sort
sortDir
Direction of initial sort
possible values: 'ASC', 'DESC'
getQueryParms
If true, check the web page's query string for filter parameters and apply any filter that is found. Filter parameters must be of the form "f[x]=" where x is the column index. (default: false)

Header Configuration

frozenColumns
number of columns on the left side of the grid that should be frozen (like Excel).
headingSort
A string that defines how headings are displayed to facilitate sorting.
hdrIconsFirst
Put sort and filter icons before or after header text (default: true)
allowColResize
Allow columns to be resized by the user? If true, then resizing for individual columns can be disabled using noResize in columnSpecs[].
ColGroups
An array of strings that can serve as secondary headings. In LiveGrid Forms, they also serve as the headings for the tabbed panels on the input form.
ColGroupsOnTabHdr
Set to 'true' for the strings in ColGroups[] to be used as secondary headings. In LiveGrid Forms, it may be set to 'false' so that ColGroups[] is only used on the input form.
AutoFilter
If enabled, an additional row is added to the grid header where column filters are placed. See the filterUI option to customize each column's filter.
FilterAllToken
The token in select filters used to indicate "show all values" (default: "___ALL___").

Cookie options

saveColumnInfo
Specifies which details to save in the grid's cookie. Only one cookie is used for each grid. Note that the width setting includes the hide/show status of the column. (default: {width:true, filter:false, sort:false})
In the .net plug-in, this option is represented by 3 separate properties: saveColumnWidth, saveColumnFilter, saveColumnSort
cookiePrefix
A string that is prepended to the cookie name. (default: 'RicoGrid.')
cookieDays
Number of days before the cookie expires. If you don't specify it, then the cookie is only maintained for the current session. (default: null)
cookiePath
Sets the top level directory from which the grid cookie can be read. If you don't specify it, it becomes the path of the page that sets the cookie. (default: null)
cookieDomain
Tells the browser to which domain the cookie should be sent. If you don't specify it, it becomes the domain of the page that sets the cookie. (default: null)

Highlighting and selection

highlightElem
a string that specifies what gets highlighted/selected
highlightSection
an integer that specifies which section of the table is highlighted
highlightMethod
Method used to highlight cells & rows. Possible values:
highlightClass
When highlighting by class, this is the class name used (default: 'ricoLG_selection')

Export and print

maxPrint
The maximum number of rows that the user is allowed to Print/Export. Set to 0 to disable print/export. (default: 1000)
exportWindow
Options string passed to window.open() when the export window is created. (default: "height=400,width=500,scrollbars=1,menubar=1,resizable=1")
exportStyleList
An array of CSS attributes that will be extracted from the first visible row of the grid and used to format all rows of the exported table. (default: ['background-color', 'color', 'text-align', 'font-weight', 'font-size', 'font-family'])

Behavior Defaults

canHideDefault
Controls whether columns can be hidden/shown (default: true). Hide/show can be disabled for individual columns using the canHide property in columnSpecs.
canSortDefault
Controls whether columns can be sorted (default: true). Sorting can be disabled for individual columns using the canSort property in columnSpecs.
canFilterDefault
Controls whether columns can be filtered (default: true). Filtering can be disabled for individual columns using the canFilter property in columnSpecs.
dndMgrIdx
Specifies which drag-and-drop management zone should be used for drag operations (default: 0). This only needs to be specified if the web page uses multiple distinct zones.

Event control

menuEvent
A string that specifies when the grid's menu should be invoked
windowResize
A boolean value specifying whether to resize the grid during a window.resize event. This should be set to false when the grid is embedded in an accordian. (default: true)

Event handles

Event handlers cannot be passed in options to the constructor, but may be set after the LiveGrid has been constructed.
sortHandler
(default: Rico.LiveGridMethods.sortHandler -- bound)
filterHandler
(default: Rico.LiveGridMethods.filterHandler -- bound)
onRefreshComplete
(default: Rico.LiveGridMethods.bookmarkHandler -- bound)
rowOverHandler
(default: Rico.LiveGridMethods.rowMouseOver -- bound as event listener)
mouseDownHandler
(default: Rico.LiveGridMethods.selectMouseDown -- bound as event listener)
mouseOverHandler
(default: Rico.LiveGridMethods.selectMouseOver -- bound as event listener)
mouseUpHandler
(default: Rico.LiveGridMethods.selectMouseUp -- bound as event listener)
onscroll
called whenever the grid is scrolled vertically. (default: null)
onscrollidle
called 1.2 seconds after the grid is scrolled vertically. (default: null)
click
called when a grid cell is clicked. (default: null, unless menuEvent='click')
dblclick
called when a grid cell is double-clicked. (default: null, unless menuEvent='dblclick')
contextmenu
called when a grid cell is right-clicked. (default: null, unless menuEvent='contextmenu')

Per-column configuration

Options for each individual column are contained in the columnSpecs option. columnSpecs is an array with an entry for each column. Each column entry can either be:
Hdg
An alternate way of specifying the heading text for a column. Only used by LiveGrid if the grid id refers to a <div> instead of an html table.
canSort
Column can be sorted. (default: grid.options.canSortDefault)
canFilter
Column can be filtered. (default: grid.options.canFilterDefault)
canDrag
Column cells can serve as the source for a drag-n-drop operation. The "DragAndDrop" module must be loaded. The temporary drag objects have a class of "LiveGridDraggable". For an example, see drag_and_drop_grid.html. (default: false)
canHide
Column can be hidden/unhidden. (default: grid.options.canHideDefault)
visible
Controls whether the column is visible at grid startup (default: true). If grid.options.saveColumnInfo.width is true and there is a value in the cookie for this column, the cookie value will take precedence.
width
An integer specifying the initial width (in pixels) for the column. Here is the algorithm LiveGrid uses for setting the initial width of each column:
  1. If options.saveColumnInfo.width is true and column information is present in the grid's cookie (due to the user previously performing a resize on that grid's column), then the width in the cookie is used. Otherwise...
  2. If there is a width spec for the column in options.columnSpecs[], then the width in the spec is used. For an example, see ex3.php/asp/aspx. Otherwise...
  3. If options.defaultWidth is true (default) and the grid header is initialized from an html table, then the column's width in the html table is used. You can usually control the column widths of the initial table by using col tags (e.g. <col style='width:40px;' >). If the total table width is less than the browser width then this works; however if it is greater, then the browser often ignores <col width> and tries to squeeze all of the columns into the available window width. Thus, using this method to set the column width is unreliable. Otherwise...
  4. If options.defaultWidth is false, then the column's width is set to options.defaultWidth (which defaults to 100).
Therefore, the most reliable way to set column widths in LiveGrid and SimpleGrid is to specify a width for every column in options.columnSpecs[]. If many columns share a common width, then you can shortcut this somewhat by setting options.defaultWidth=false, and setting options.defaultWidth to the common width.
noResize
Allow column to be resized? (default grid.options.allowColResize )
ClassName
By default, LiveGrid assigns a unique CSS class name to each column, which follows the naming convention: table_id + '_col' + column_index. For example, the fourth column in the grid 'mygrid' would have the class name 'mygrid_col3'. The value of the ClassName option overrides this default name. The ClassName option is most commonly used to specify column alignment via the Rico-provided 'alignright' and 'aligncenter' classes. So, if you wanted the first 3 columns in your grid to be displayed with white text on a red background, you could do either of the following:
In CSS:
.mygrid_col0 div.ricoLG_cell, 
.mygrid_col1 div.ricoLG_cell, 
.mygrid_col2 div.ricoLG_cell {
  color: white;
  background-color: red;
}
OR
In CSS:
.WhiteOnRed div.ricoLG_cell {
  color: white;
  background-color: red;
}

In javascript:
columnSpecs : [{ClassName:'WhiteOnRed'},
               {ClassName:'WhiteOnRed'},
               {ClassName:'WhiteOnRed'},
               ...
Finally, please note that this ClassName is not applied to the grid headings - use a align="right" on the <th> tag to accomplish the header alignment.
type (DataType in .net plug-in)
A string containing one of these values:
control
An object that can be used to provide special formatting for a column. Several column controls are provided with LiveGrid. The code for them resides in ricoLiveGridControls.js. Here is a brief description of the provided controls:
Rico.TableColumn.checkboxKey(showKey)
Display unique key column as: <checkbox> <key value> and keep track of which keys the user selects. Key values should not contain <, >, or &.
Rico.TableColumn.checkbox(checkedValue, uncheckedValue, defaultValue, readOnly)
Display column as checkboxes. Database column should contain only two-values (e.g. yes/no). The following code is taken from ex7 (column values are 1 and 0):
columnSpecs: [{canHide:false,
               control:new Rico.TableColumn.checkbox('1','0'),
               ClassName:'aligncenter'},
              'specQty'],
Rico.TableColumn.textbox(boxSize, boxMaxLen, readOnly)
Display the column value in a text box.
Rico.TableColumn.HighlightCell(chkcol,chkval,highlightColor,highlightBackground,chkop)
Highlight a grid cell when a particular value is present in the specified column. chkop optionally specifies the comparison to be performed: ==, !=, <, <=, >, >=. If not specified, then == is used. The following code is taken from ex2highlight and highlights the entire row when column 1 contains "HANAR":
var CustId='HANAR';
var CustIdCol=1;
var highlight=Rico.TableColumn.HighlightCell;
...
columnSpecs: [
{ control:new highlight(CustIdCol,CustId,'red','yellow') },
{ control:new highlight(CustIdCol,CustId,'red','yellow') },
{ control:new highlight(CustIdCol,CustId,'red','yellow') },
{ control:new highlight(CustIdCol,CustId,'red','yellow') },
{ control:new highlight(CustIdCol,CustId,'red','yellow') },
{ type:'date', control:new highlight(CustIdCol,CustId,'red','yellow') },
{ type:'date', control:new highlight(CustIdCol,CustId,'red','yellow') }]
Rico.TableColumn.bgColor()
Database value contains a css color name/value
Rico.TableColumn.link(href,target)
Database value contains a url to another page. The href parameter may contain references to grid values by including "{x}" in the string, where x is a column number. The following code is taken from ex6:
columnSpecs: [,
{control:new Rico.TableColumn.link('ex2.asp?id={0}','_blank'),
 width:250},
,'specQty']
Rico.TableColumn.image()
Database value contains a url to an image. The following code is taken from photos.php:
imgctl=new Rico.TableColumn.image();
...
columnSpecs: [
{control:imgctl,width:90},,,
{type:'datetime'},{width:200}]
Rico.TableColumn.lookup(map, defaultCode, defaultDesc)
Map a database value to a display value
Rico.TableColumn.MultiLine()
Overcomes issues when displaying multi-line content (i.e. content with <br> tags) in IE6 and IE7

It is also possible to write your own column control, which implements logic specific to your application. Here is an example:
// Display values white on black if
//   first column contains the value "reverse"
// Usage: { control:new MyCustomColumn() }
MyCustomColumn = Class.create();

MyCustomColumn.prototype = {
  initialize: function() {},

  _clear: function(gridCell,windowRow) {
    gridCell.style.color='';
    gridCell.style.backgroundColor='';
    gridCell.innerHTML='&nbsp;';
  },

  _display: function(v,gridCell,windowRow) {
    var col0=this.liveGrid.buffer.getWindowValue(windowRow,0);
    if (col0=="reverse") {
      gridCell.style.color='white';
      gridCell.style.backgroundColor='black';
    } else {
      gridCell.style.color='';
      gridCell.style.backgroundColor='';
    }
    gridCell.innerHTML=this._format(v);
  }
}
filterUI
If the AutoFilter option is enabled for the grid, then filterUI will control how each column is filtered. If filterUI is:
filterCol
Specifies that the filter should be applied to a different column. For example, ex3livegrid.asp/aspx/php uses this feature to filter the order and ship date columns by year. The full date is shown in the column in which the filter appears; however, there is another hidden, calculated column containing "year(orderdate)" to which the filter is applied.
Number formatting:
multiplier
The value is multiplied by this number before it is displayed. (default: 1)
decPlaces
Number of places to the right of the decimal point. (default: 0)
thouSep
Boolean indicating whether to insert thousands separator. (default: true)
negSign
Specifies how negative numbers should be displayed. Possible values:
prefix
A string added to the beginning of the number. Typically a currency symbol.
suffix
A string added to the end of a number. For example, a "%" symbol.
Date formatting:
dateFmt
A string specifying how the date or datetime should be displayed. Default is "translateDate", which means that the dateFmt and timeFmt strings in the RicoTranslate object are used (this defaults to "mm/dd/yyyy" for dates and "mm/dd/yyyy hh:nn:ss a/pm" for datetimes, but is overridden by the various language translation files). If dateFmt="localeDate", then the value is formatted using javascript's built-in toLocaleDateString() function. If dateFmt="localeDateTime", then the value is formatted using javascript's built-in toLocaleString() function. The dateFmt string may contain the following special character sequences:
// display first column as "month year"
columnSpecs : [{type:date, dateFmt:'mmm yyyy'}]
prefix
A string added to the beginning of the date.
suffix
A string added to the end of a date. For example, you could use this to include a time zone:
// indicate that times are GMT/UTC
columnSpecs : [{type:datetime, suffix:' UTC'}]