Salesforce: Javascript and Remoting to force Lightning Page refresh

on

I want to write about one of the most frustrating and annoying Salesforce’s issues of the last period: PageReference commands do not trigger the refresh of the Lightning pages.

When in Classic you return a PageReference from Apex to a Visualforce page, it redirects you to the Salesforce page by refreshing the layout. It is really useful since you can manage your backend business logic (i.e. updating fields, change record types) and directly checking the results.

Due to the Salesforce Lightning caching, the PageReference does not refresh the Lightning page related to an object (i.e. Case, Account, etc.). Especially if you were previously in the same context.

It means that buttons or actions that return a PageReference will not trigger the refresh. It could be a problem, especially if you update record types that are expected to change the object page layout.

You can solve the problem in two ways:

  • Developing your buttons by using Lightning components
  • Using Visualforce pages with javascript and remoting to force the refresh

The second one is a smart trick to continue working both on Classic and Lightning. The recipe requires only three ingredients:

  • A Visualforce page
  • Javascript
  • Apex Remote function

Visualforce page

The Visualforce page will contain the HTML elements, such as buttons, the Remote Controller reference (extensions=”YOUR_REMOTE_CONTROLLER”), and the Javascript to call the remote functionalities.

Javascript

The Javascript code is the core of the Visualforce Page. It recalls the Remote function through the instruction Visualforce.remoting.Manager.invokeAction.

It is an asynchronous method and the callback code forces the refresh. Based on the environment we are working on, it triggers the right refreshing method:

  • Lightning: sforce.one.navigateToSObject(caseId);
  • Classicwindow.parent.location = ‘/’ + caseId;

Apex Remote function

The Apex Remote controller is very simple. It provides a global static function, called into the previous javascript code. You can develop your business logic inside, like updating fields or record types to switch page layouts. Just remember to add the annotation @RemoteAction

 

(Visited 1,005 times, 7 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *