Search This Blog

Wednesday, May 7, 2014

VisualForce - Make Remote Action Call from Static Resource

Remote Action in Visual Force gives us the ability to make a call asynchronously to the salesforce controller and handle the response in a callback function without making the complete page refresh or waiting for an action. Basically in terms of HTML, this can be treated as an ajax call made through the script tags.

Controller

Lets check the controller now and assume that the namespace of the package is 'namespace'.
  1. global class ControllerName {
  2.    @RemoteAction
  3.     global static String MethodName(Paramters....)
  4.     {
  5.         return 'Hello';
  6.     }
  7. }
All the remote actions are annotated and static.



VF Page

The syntax for making a remote action call in a VF Page is as below.
  1. <apex:page controller="ControllerName">
  2.    <script>
  3. Visualforce.remoting.Manager.invokeAction(
  4. '{!$RemoteAction.ControllerName.MethodName}', [Parameters],
  5. function(result, event){
  6. //In this callback function the response is handled in aync
  7. });
  8. </script>
  9. </apex:page>
The prefix to the controller name (!$RemoteAction) will append the corresponding namespace of the controller. Line 2 invokes the Remoting Manager which is implemented by salesforce and then makes an ajax call to that particular controller after appending some metadata.

From a Static Resource

But what if this needs to be added into static resource? This same piece of code will not work if moved into a static resource. There will be an error TypeError: Cannot read property 'ControllerName' of undefined at Object.$VFRM.Util.getObject

This is because every VF page or componet has a scope and context but there is no scope or context for a static resource. Also the the merge field(!$) cannot be interpreted by the static resource. So the above method in VF page has to be updated a little.

Static Resource named RemoteTest.resource

  1. ControllerName.MethodName([Parameters], 
  2.        function(result, event){
  3.              //In this callback function the response is handled in asyn.
  4. });

Updated VF Page to include the static resource

  1. <apex:page controller="ControllerName">
  2.    <apex:includeScript value="{!$Resource.RemoteTest}" />
  3. </apex:page>
But after some research it is still found that even now there is the same error if there is namespace for the package. When a static resource is included in the page, namespace of the package will be added to the js file name also as below when the page is rendered.

Because of this, the controller methods will be available with the syntax namespace.controller.method

Updated static resource

  1. NameSpace.ControllerName.MethodName([Parameters], 
  2.        function(result, event){
  3.              //In this callback function the response is handled in asyn.
  4. });

No comments:

Post a Comment