extjs & visualforce (part 2), JSON this time

Posted by in apex, salesforce, visualforce

Let me preface this post by stating that the following is merely a proof of concept and should not necessarily be implemented into a production org. The pagination demonstrated below is not fit for large datasets and may result in unexpected behavior!

Rich Waters’ comment on my first post re: Ext JS & visualforce got me thinking about the possibilities of leveraging JSON in Ext JS components within Visualforce, so I implemented a paging grid, similar to this example provided by Ext JS. OK, enough of the formalities, I suppose people want to see what kind of development ensued:

The magic behind the grid is JSON being delivered by a Visualforce page called “Json_test”:

<apex:page contentType="text/html" showHeader="false" controller="Json_File" >
	<apex:outputText value="{!json}" />

The controller (spits out the JSON):

public class Json_File {
	public string json {get;set;}
	public Json_File() {		
        opportunity[] opps = new opportunity[]{};

	integer start = 0;
	integer pageSize = 10;

	if (ApexPages.currentPage().getParameters().get('start') != null &amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp; ApexPages.currentPage().getParameters().get('limit') != null) {
		start = integer.valueof(ApexPages.currentPage().getParameters().get('start'));
		pageSize = integer.valueof(ApexPages.currentPage().getParameters().get('limit'));
        string jsonRecordsString = '';
        integer i = 1;
        integer j = 0;
        for (Opportunity o : [Select id, name, stagename, closedate from opportunity order by name limit 1000]) {
			if (j >= start) {
				if (i <= pageSize) {
					jsonRecordsString += '{';
					jsonRecordsString += '"id":' + '"'+o.id+'",';
					jsonRecordsString += '"name":' + '"'+o.name+'",';
					jsonRecordsString += '"stagename":' + '"'+o.stagename+'",';
					jsonRecordsString += '"closedate":' + '"'+o.closedate+'"';
					jsonRecordsString += '},';
		string jsonString = '({"total":"'+opps.size()+'", "results":[' + jsonRecordsString + ']})';
        jsonString = jsonString.replaceAll(',]',']');
        this.json = jsonString;

Finally, the grid itself (from the Visualforce page embedded above in this post):

*It’s important to note that this Visualforce page does not have a controller; the JsonStore provides the reference needed (url) [see below] to access the future backend of the grid.

<script type="text/javascript">
	var opportunity_grid;
		function() {				
			//prevents mixed content message in ie
			Ext.BLANK_IMAGE_URL = '/s.gif';
			Ext.SSL_SECURE_URL = '/s.gif';
	function render_queue() {
		// create the data store
		var store = new Ext.data.JsonStore({
			totalProperty: 'total',	// total data, see json output
			root: 'results',	// see json output	
			url: 'http://crmmanager-developer-edition.na6.force.com/test/Json_test', 			
	        fields: [
	           {name: 'id'},
	   			'name', 'stagename', 'closedate'

		var pagingBar = new Ext.PagingToolbar({
	        pageSize: 10,
	        store: store,
	        displayInfo: true,
	        displayMsg: 'Displaying opportunities {0} - {1} of {2}',
	        emptyMsg: "No opportunities to display"
		var gridView = new Ext.grid.GridView({ 
				forceFit: true
	    opportunity_grid = new Ext.grid.GridPanel({
	        store: store,
	        columns: [
	            {header: "name", width: 150, dataIndex: 'name', sortable: true},
	            {header: "stage", width: 150, dataIndex: 'stagename', sortable: true},
	            {header: "close date", width: 150, dataIndex: 'closedate', sortable: true}
	        loadMask: true,
	        bbar: pagingBar,
	        view: gridView,
	        layout: 'fit'
		try {			
		} catch(e){}	
		store.load({params:{start:0, limit:10}});									

As you can see, the Json_File controller accepts two params (start, pageSize), which are sent from the store in store.load() to manage the index of the query and the number of records returned. Unfortunately, Salesforce does not provide an “INDEX” keyword in SOQL, which would make this pagination much more “resource respectful” (each time page up/page down is called from the paging grid, we receive a full dataset from Salesforce which, as you might guess, can be dangerous for tables with more than a thousand records).

I looked into the possibility of leveraging StandardSetController, but given the out-of-box architecture of the paging grid, we’d still be calling our JSON controller each time the grid was “paged”, which effectively calls the entire dataset.

I’m open to ideas, so please weigh in.

EDIT: the source for the above example…