Simple Dojo Grids

By on November 6, 2007 10:16 am

Grid browser

We’re excited about the release of Dojo 1.0. In honor of the new release, I’m starting a series on one of the newest additions to the Dojo mix: the Dojo Grid.

When demonstrating Dojo, I prefer tying examples to real-world scenarios. Imagine for a moment that we work at a company that produces gaskets out of sheet material. Each of these gaskets has a part number, a minimum temperature rating, a maximum temperature rating, and maximum pressure rating. Each of these attributes needs to be a column so they can be displayed and sorted so customers can find the information they need in a timely manner. Let’s take a look at how the data looks:

var data = [
	/* part #, min T rtg, max T rtg, max P rtg */ 
	[ '4001', -946, 931, 647 ],
	[ '4002', -601, 1894, 208 ],
	[ '4003', 456, 791, 132 ],
	[ '4004', -259, 2433, 840 ],
	...
];

For the purposes of these exercises, we’ll put the entire set of data into a file data.js. As a disclaimer, the data was randomly generated and doesn’t represent anything real.

Suppose we want to display data in a tabular format and we select the feature-rich Dojo Grid. First, we need to create a model for the data. A quick review of the models the grid provides makes dojox.grid.data.Table a logical choice because it handles data as a list of lists. We’ll delve into the different models later, but for now, assume this is a suitable model.

var model = new dojox.grid.data.Table(null, data);

Next, we need to define the grid structure or layout. This represents the data view. Our structure object is:

var cell = { name: 'Cell Name' };
var subrow = [ cell ];
var view = { rows: subrow };
var structure = [ view ];

A structure is a list of views, a view is an object that contains a list of subrows named ‘rows’, and a subrow is a list of cells. When displaying our example, a list of gaskets, we need one view, one subrow, and four cells:

var subrow = [
	{ name: 'Part Number' },
	{ name: 'Minimum Temperature (F)' },
	{ name: 'Maximum Temperature (F)' },
	{ name: 'Maximum Pressure' }
];

var view = {
	rows: [ subrow ]
};

var structure = [
	view
];

Now that we have our data in the model and we’ve defined the data appearance, let’s create a grid:

We have a grid that displays our data. That’s just the beginning.

The first improvement suggested is temperatures are missing the degree symbol, °, so let’s add that. Each cell in a subrow can have a formatter property, a function to format the displayed data:

function formatDegrees(value){
	return value + '°';
}

var subrow = [
	{ name: 'Part Number' },
	{ name: 'Minimum Temperature (F)', formatter: formatDegrees },
	{ name: 'Maximum Temperature (F)', formatter: formatDegrees },
	{ name: 'Maximum Pressure' }
];

Our updated grid displays temperature units. This is great! We have a grid that sorts our data and displays it the way we want.

For our next order of buisness, suppose that the president of the company, Bob, wants the minimum temperature displayed above the maximum temperature. Not a problem!

Review the view and subrow. View has a property named rows which is an array of sub-rows which is itself an array of cells. The sub-rows form a mini table in each row of the grid. And just like HTML tables, the cells of sub-rows can be spanned across rows:

var subrow1 = [
	{ name: 'Part Number', rowSpan: 2 },
	{ name: 'Minimum Temperature (F)', formatter: formatDegrees },
	{ name: 'Maximum Pressure', rowSpan: 2 }
];
var subrow2 = [
	{ name: 'Maximum Temperature (F)', formatter: formatDegrees }
];

var view = {
	rows: [
		subrow1,
		subrow2
	]
};

Bob should be pleased with the resulting grid. But Bob is particular, and now suggests that the rating columns are a bit too wide, and the part number needs prominence. This requirement is easily satisfied by defining a width property on each cell of a sub-row that contains a valid CSS width:

var subrow1 = [
	{ name: 'Part Number', rowSpan: 2 },
	{ name: 'Min. Temp. (F)', formatter: formatDegrees, width: '60px' },
	{ name: 'Max. Pressure', rowSpan: 2, width: '60px' }
];
var subrow2 = [
	{ name: 'Max. Temp. (F)', formatter: formatDegrees, width: '60px' }
];

We have a grid that makes Bob happy, for now. Next week, we’ll tackle more feature requests from Bob, like inline images and sub-grids, and we’ll go over the different models that the Grid provides.

This article would not be complete without a gratuitous iPhone grid screenshot:

Grid iPhone

Comments

  • Les

    Thank you for the article.

    How can I enable sorting for specific columns?
    Can I provide a sort function for a column?

  • Les, you would do something like this:
    model.fields.get(column_number).compare = new_sort_function;

  • Les

    Bryan, I’d like to provide a sort function in the same way entered formatter, e.g.:

    { name: ‘Max. Temp. (F)’, formatter: formatDegrees, sort: sortDegrees, width: ’60px’ }

    … but it won’t work for me. Am I doing something wrong or this is not possible?

  • Pingback: SitePen Blog » Blog Archive » Dojo Grids: Diving Deeper()

  • Thank you for doing this. This is exactly the kind of thing that dojo needs!

  • grid is working fine with json, but a little confused on how to tie it to an XmlStore?

  • kris

    Hi need your help. i am using Aptana IDE but there seems to be a problem. i can’t make it work. the only thing that appears on the screen are the headers. but the data contained in the “data.js” is not displayed. also i can’t locate where is the “general.css”. could this be the cause of the problem?

    thank you for your time and i would really appreciate it if anybody can help me.

    newbee. :-)

  • There is a serious problem in this tutorial. The very first table, where there is only one subrow, everything is fine. When you add a new subrow, the data is getting messed up. For example, for the first product, the max pressure is 647. If you look at the final example, max temp is showing as 647 and max pressure is showing the min temp instead.

  • zak

    I tried the grid_basic.html example on my machine but it only displays data up to part # 4025 only and if I update the data, it doesn’t pick it up. What am I doing wrong?

  • zak

    don’t worry about it! I saved it wrong.

  • Manjul

    I wanna know that how I can link a dojo grid with JSON data set, that JSON data set I want to update using AJAX call. Or suggest me if any other way to accomplish the same need.

    thanks

  • ewilde

    regarding the iPhone screenshot:
    if I write code that works in the Windows version of Safari, is it more or less guaranteed to work the same in the iPhone?
    is this browser installed in the iPhone is really Safari 3.x, or it’s just so called “based on…”?

    Thanks!

  • ewilde: My slides from a recent talk, http://securimetric.net/library/iPhoneDojo.pdf , give full details, but the short answer is, it depends on the feature set.

  • liquid

    Thanks for the article. Is it possible to have dojo progress meter in a grid column?
    And also how to add rows dynamically?
    thanks

  • Yogesh

    Hey thank you bryan for showing me the way to go for grid thanks alot GR8 tutorial

  • Anil Soni

    Chris,

    Brena,
    I need your help.
    I want to make column field editable, here I am setting the editable properties for specific field under this.layout by using editable: “true” .
    like this : –
    this.layout = [[
    { name: ‘Name’, field: ‘columnId’, width: “25em” },
    { name: ‘ Column Name’, field: ‘columnName’, width: “25em”, editable: “true” },
    ]];
    can you please tell me what other things need I change to make this running.

    Quick response will be much appreciable.

  • arun_rocky

    hi,
    I am passing values from a Json obect to grid. when i am passing 234.50 to grid, in grid its displaying values only as 234.5 i like to display the whole value which i am passing through json object.

  • Matthew Shirey

    In response to “Bibhas B”, I made a minor change to the subrows to get the data to display in the proper columns when using multiple subrows:

    var subrow1 = [
      { field: 0, name: 'Part Number', width: 'auto', rowSpan: 2 },
      { field: 1, name: 'Min. Temp. (F)', width: '100px', formatter: formatDegrees },
      { field: 3, name: 'Max. Pressure', width: '100px', rowSpan: 2 }
    ];
    
    var subrow2 = [
      { field: 2, name: 'Max. Temp. (F)', width: '100px', formatter: formatDegrees }
    ];
    

    — Matthew

  • wuminqi

    Does dojo grid support complex table view?

    Such as group a set of columns and give a general header for this group.According all the demos i saw, a header must have a column linked with it.

  • pb

    Hello,
    I need some sugession om how to bridge Zend with Dojo. Currently I an using zend MVC framework and I have a function that return a some value from a mysql db. I then display the data using an HTML table.

    How Do I do this using the dojo Grid. The data is not static.

    Thanks for any help

  • Hello,

    I am using xhrPost to get the data from the servlet. The JSON string is in response body.

    Now how do you expect me to use this JSON string which has 2 rows (say) with 5 columns(cola, colb, colc, cold, cole). And I want to create the Grid on the fly. no static coding of the Grid.(it has portlet render problem,- if i hardcode my grid)

    Can you please provide a complete code so that i can refer that and use it in my JSP.

    Thanks.

  • Pingback: Simple Dojo Grid « i xfree()

  • zqm

    why not publish a demo include all source ,for example
    “《script src=”Dojo/dojo.js”》《/script》”

  • If someone want to create and populate dojo grid in Zend framework. visit my article

    http://zendguru.wordpress.com/2009/01/08/dojo-grid-in-zend-framework-creating-nice-and-cool-grid-in-php-using-zend-framework-and-dojo/
    You will find this article very helpful if you are working in Zend Framework and want to use dojo grid.

  • cingusoft

    Hi

    i have a simple question,
    i have a table and i want Grid to renderize this table.
    how is possible this?

    thanks in advance for your help

  • Is the Grid better visible on iPhone? ;)

    Decent write-up!

  • Saurabh

    Hi:

    How to do the same thing if i have data as an object returned by Ajax request instead of a file.

    Thanks
    Saurabh

  • Hi

    Im using dojo 1.4 and i need to load or reload a grid from a data store from php. I “echo” a string (in buildGrid.php) like

    {identifier: ‘id’,label: ‘id’,items:[{col1: “celda1”,col2: “celda2”,col3: “celda3”,col4: “celda4”},{col1: “celda5”,col2: “celda6”,col3: “celda7”,col4: “celda8”}]}

    The grid in the html is defined as:

    and the javascipt onclick function as:

    function populateGrid() {
    grid = dijit.byId(“grid”);
    var url = “Ajax/buildGrid.php”;
    gridtStore = new dojo.data.ItemFileReadStore({url: url});
    grid.setStore(gridtStore);
    grid.startup();
    return;
    }

    But i get a “Sorry, an error ocurred” message :S

    Thx!

    Daniel M

  • The only times I have seen the “Sorry, an error occurred” message with grids is when I have duplicate entries in the grid. Check to make sure that all entries are unique (your example above shows unique values – but also says that your data is “like” that shown….perhaps not quite??)

    If duplicates exist AND you need them to exist, try removing the “query:{…}” entry from your grid definition and see if that doesn’t work.

    Hope this helps

  • …and the “identifier: from your JSON (identifiers should be unique – else not much of an identity)…

  • David Dewar

    I believe that this code no longer works with the standard Dojo 1.5 release. In the 1.5 release, there is a gzip archive called ‘compatGrid.tar.gz’ in dojox/grid that appears to include the code modules referenced in the examples:
    dojo.require(“dojox.grid.Grid”);
    dojo.require(“dojox.grid._data.model”);

    Cheers,

    David

  • James

    The examples do not work in Google Chrome.

  • How can I make those examples work in Google Chrome?