Category Archives: DOJO

How to add sort icon by default on Dojo DataGrid?

I was working on some applications with heavy customizations of Dojo DataGrid involved, which is cumbersome if the API doesn’t provide good features exposed to the developers like me (may be like you ☺). Unfortunately the application has DataGrids in multiple places with more custom features, so I couldn’t get my hand to migrate it to EnhancedDataGrid. It should’ve been done earlier; my job could’ve been simpler. 

One of the simple expected features was to set the sort icon by default or wherever the sort icon is required. After searching in many forums including dojofoundation and stackoverflow I couldn’t find a straightforward method or API. So I had to do it on my own without adding much complexity in the existing code. Here is what I did,

As you see above, the function has two parameters one is the Grid (dijit based object), and the field name (data field from your data store). You can also use index based sort icon. Thanks to DOJO, the DataGrid has layout API exposed which would help any developer to play and customize the grid like they want. 

Step by step explanation of the code and how I came to this solution,

  • I loop through the cells that are part of the layout API and find out the column I want based on the field name comparison. Could be index-based comparison as well.
  • I’m using jQuery for all my DOM manipulations. You can use DOJO as well for your DOM. Based on the cell id I’ve created a jQuery object (targetCell) to perform some DOM changes over the cell.
  • Setting the ARIA (Accessibile Rich Internet Applications) attribute to ascending (could be descending).  Setting this attribute tells the screen reader that the column in ascending order.
  • Every cell has a sort node (div element) in it. It has to be replaced with the sort icon code. Once the sort node is found, the Sort DOM structure should be added.
  • I have added the sort DOM structure to the sort node to render it properly with the sort icon and the column label.
  • After adding the DOM structure, this sort information has to be informed to the Grid using setSortIndex. Then only it would reflect or render the sort icon when you click other columns. The second parameter should be false, otherwise the grid will sort the data again.

I hope you find this simple and easy. From the forums I read, there could be other ways to do it. Leave your suggestions in the comments section.