Published on
June 8, 2016

Setup a consultation

How To Auto-Refresh A Page In Salesforce Using Streaming API

We come across many situations where we would want a web page to auto-refresh. Imagine watching your favourite team play a nail biter and you have to hit the refresh button every 10 seconds. Auto refresh is also needed in Salesforce, whether it might be dashboards, reports or list views. We know that when we are on the list view screen of any object, we will have to hit the refresh button to see the newly created records. Wouldn't it be ideal if the list view updates itself whenever a new record is created?

We can achieve this using an action poller. The drawback here is, irrespective of whether a new record is created or not, the page will refresh based on the time interval set. This means that the server is hit even when it is not required.

This is where Streaming API comes to the rescue. Streaming API works on push technology.  Push Technology is commonly defined as “Push, or server push, describes a style of Internet-based communication where the request for a given transaction is initiated by the publisher or central server. It is contrasted with pull/get, where the request for the transmission of information is initiated by the receiver or client.” So instead of using action poller, which works on pre-set time interval, we rely on Salesforce API which will notify when there is an event.

We have taken an example from Salesforce Streaming API guide and tailored it to suit this requirement.

Step 1: Create Topic

First of all we will have to create a topic or event, creation, update, delete, or undelete of a record, for which we need notification.

1. Select Your Name >Developer Console.

2. Click Debug >Open Execute Anonymous Window.

3. In the Enter Apex Code window, paste in the following Apex code, and click Execute.

PushTopic pushTopic = new PushTopic();

pushTopic.Name = ‘RefreshAccounts’;

pushtopic.Query = 'SELECT Id, Name FROM Account';

pushTopic.ApiVersion = 33.0;

pushTopic.NotifyForOperationCreate = true;

pushTopic.NotifyForFields = 'Referenced';

insert pushTopic;

Please refer to Event Notification Rules to know more.

Step 2 Subscribe to the Topic

1. In your browser, navigate to https://developer.salesforce.com/page/Workbench

2. For Environment, select Production.

3. For API Version, select 33.0.

4. Accept the terms of service and click Login with Salesforce.

5. Once you successfully establish a connection to your database, you land on the Select page.

6. Click queries >Streaming Push Topics.

7. In the Push Topic field, select RefreshAccounts.

8. Click Subscribe.

You’ll see the connection and response information and a response like "Subscribed to /topic/RefreshAccounts"

Step 3 Create Static Resources

1. Download the CometD compressed archive (.tgz) file from http://download.cometd.org/cometd-2.2.0-distribution.tar.gz.

2. Extract the following JavaScript files from cometd-2.2.0-distribution.tar.gz:

  • cometd-2.2.0/cometd-javascript/common/target/cometd-javascript-common-2.2.0.war
  • cometd-2.2.0/cometd-javascript/jquery/src/main/webapp/jquery/jquery-1.5.1.js
  • cometd-2.2.0/cometd-javascript/jquery/src/main/webapp/jquery/json2.js
  • cometd-2.2.0/cometd-javascript/jquery/src/main/webapp/jquery/jquery.cometd.js

To extract the .tgz file in the Windows environment, you’ll need a utility such as PowerArchiver, 7–zip, or Winzip.

3. Extract cometd.js from cometd-javascript-common-2.2.0.war by using the following shell commands:

cd cometd-2.2.0/cometd-javascript/common/target

jar xvf cometd-javascript-common-2.2.0.war org/cometd.js

4. From Setup, click Develop >Static Resources to add the extracted files with the following names:

File Name                     Static Resource Name

cometd.js                     cometd

jquery-1.5.1.js              jquery

json2.js                         json2

jquery.cometd.js        jquery_cometd

Step 4 Controller

public class StreamingAPIController

{

public StreamingAPIController()

{

}

/* Every time page is rendered, we can fetch the data on whichever criteria we want and return it back to the page. Here we are returning list of all the accounts. */

public List<Account> getRefreshedAccount

{

get  {

return [select Id, Name from Account LIMIT 50000] ;

}

set;

}

}

Step 5 Creating a visual force page

<apex:page id="page" controller="StreamingAPIController">

<apex:form id="form">

<apex:includeScript value="{!$Resource.cometd}"/>

<apex:includeScript value="{!$Resource.jquery}"/>

<apex:includeScript value="{!$Resource.json2}"/>

<apex:includeScript value="{!$Resource.jquery_cometd}"/>

<apex:actionFunction name="GetRefreshedAccounts" reRender="page,pageBlockTable"/>

<script type="text/javascript">

(function($) {

$(document).ready(function() {

// Connect to the CometD endpoint

$.cometd.init({

url: window.location.protocol+'//'+window.location.hostname+'/cometd/24.0/',

requestHeaders: { Authorization: 'OAuth {!$Api.Session_ID}'}

});

// Subscribe to a topic. JSON-encoded update will be returned in the callback

// In this example we are using this only to track the generated event

$.cometd.subscribe('/topic/RefreshAccounts', function(message) {

//You can use message as it will return you many attributes

//We are calling the Action Function here.

GetRefreshedAccounts();

});

});

})(jQuery)

</script>

<apex:pageBlock id="pageBlock">

<apex:variable var="count" value="{!0}" />

<apex:pageBlockTable id="pageBlockTable" value="{!getRefreshedAccount}" var="account">

<apex:column headerValue="S.No.">

<apex:variable var="count" value="{!count+1}" />

{!count}

</apex:column>

<apex:column value="{!account.Name}" headerValue="Name"/>

</apex:pageBlockTable>

</apex:pageBlock>

</apex:form>

</apex:page>

This is a simple visual force page which will show a list of all the accounts. This page will refresh whenever a new account is created and show it in the list.

We can design a visual force page and have the controller return the data based on our requirement.  We just have to create a topic and subscribe to it. Salesforce Streaming API will take care of the notification.