Site Navigation

Apr 23, 2008

Grabbing a Grid Row with Dojo 1.1

I'm working on a project in the Dojo 1.1 JavaScript framework at work. The framework is very comprehensive and powerful. It has all the widgets of a Visual Basic or Java Swing. However, at this stage of its development, let's say the documentation could be a little better.

So I'm using the Dojo Grid widget to view some tabular data. What I needed to do was allow a user to select a row from the grid and then click on a button. This pops up a dialog with the data in a form for the user to edit. Well I figured it out, but it wasn't easy. So I thought I should post this code example for any other poor souls trying to do the same thing. Here is the code.

   1:<div id="grid" dojoType="dojox.Grid" model="model" structure="structure"
   2: autoWidth="true"></div>
   3:<button dojoType="dijit.form.Button" id="updateButton">Update
   4: 
   5:<script type="dojo/method" event="onClick">
   6:    var row = dijit.byId('grid').selection.getSelected()[0];
   7:    var selected = dijit.byId('grid').model.data[row];
   8:
   9:    if (selected) {
  10:      dijit.byId("someFormField").setValue(selected[0]);
  11:    }
  12:</script>
  13:</button>

The real heart of the issue is on line 6 and 7. First, you need to use the Dojo dijit.byId() function to grab the grid and get the selected row. This returns a integer number identifying the row in the grid. You then pass this number to the data model which returns an array containing the row data.

On lines 9 to 11, array data is assigned to the form text field. Note I check to see if selected is not empty first. If a row has not been selected, the selected array will be empty and this will cause an error if you try to assign it to the field. If there is data in the array, then line 10 assigns the first column in the row to the field identified by its ID.

I saw examples that identified the column in the grid by its name, but I could not get that to work. Using the column index numbers seems to be the only method that works for me.

I hope this will help others trying to do the same thing. Good luck!

Post a Comment

Favorite Links Feed