January 31, 2008 17:00
by
Jorge
I've recently been trying the impressive ExtJS javascript library. While looking into how our products can benefit from ExtJS's features, one of the challenges I found is the fact that some of our ExtJS grids are dynamic in the sense that the properties of their columns - number of columns, data types, formatting, etc. - are only known at run time.
In this post I will demonstrate one of the approaches you can take for sending the column models for the grids, as well as the field definitions for their data stores, from the server-side code.
For any page containing one or more data grids, the approach is a two-step process. I first use an AJAX request to download the column models for the grids and fields definitions for their data stores. Once the request is complete, I proceed to set up the grids and download their data.
Although my server code is written in C#, the approach is valid for any other languages or technologies you might use. On the client side I just sort the calls so I get the settings for the grid and data store before getting the actual data.
The first request gets to the server and is routed to the GetGridSettings function:
1: private string GetGridSettings()
2: {
3:
4: StringBuilder sb = new StringBuilder();
5:
6: // Grid name
7: sb.Append("[['myGrid'],[");
8: // Grid columns
9: sb.Append("{id:'firstname',header: 'First Name', width: 200, sortable: true, dataIndex: 'first_name'},");
10: sb.Append("{id: 'lastname', header: 'Last Name', width: 200, sortable: true, dataIndex: 'last_name'},");
11: sb.Append("{header: 'Email Address', width: 200, sortable: true, dataIndex: 'email_address'}");
12: sb.Append("],");
13: // Data Store fields
14: sb.Append("[{name: 'first_name'},{name: 'last_name'},{name:'email_address'}]");
15: sb.Append("]");
16:
17: return sb.ToString();
18: }
GetGridSettings is where you build your column model and data store fields. From here you can call into any containers you are using to keep your columns information.
The second request gets routed to GetGridData, which simply retrieves the data for the grid:
1: private string GetGridData()
2: {
3: StringBuilder sb = new StringBuilder();
4: int rowCount = 50;
5:
6: sb.Append("{rCnt:" + rowCount.ToString() + ",rows:[");
7:
8: for (int i = 0; i < rowCount; i++)
9: {
10: sb.Append("{'first_name':'John','last_name':'Doe" + i.ToString() + "','email_address':'JohnDoe" + i.ToString() + "@gmail.com'},");
11: }
12:
13: sb.Append("]}");
14:
15: return sb.Replace(",]}","]}").ToString(); // Remove the extra comma before sending the data.
16: }
And that's all for the server-side code.
Download Visual Studio project with functioning sample code: DynamicGrid.rar (528.43 kb)
Update: I just learned there's a user extension to the ExtJS GridPanel that greatly helps address the challenge I talk about in the article.