ActionFunction and ActionSupport in Salesforce - When to use what?
Most of the newbies in Salesforce are confused regarding the usage of <apex:actionSupport> and <apex:actionFunction> tags. Lets take a brief overview about what they are and when to use what.
<apex:actionSupport> - This component is used when you want to provide AJAX support to a another component. For example, on click of an image , we need to call an apex function.
So, in between start tag and end tag of our image, we can put an action support component. We need to specify the javascript event, for example onclick event and the apex action which needs
to be called when this event happens.
<apex:page controller="ActionController">
<apex:form >
<apex:image url="https://login.salesforce.com/img/logo190.png">
<apex:actionSupport action="{!methodInApex}" event="onclick"/>
</apex:image>
</apex:form>
</apex:page>
public class ActionController {
public void methodInApex(){
System.debug('Inside methodInApex');
}
}
Now the question arises that the same requirement can be fulfilled using <apex:actionFunction> component also, then why use actionSupport? When to use what?
<apex:page controller="ActionController">
<apex:form >
<apex:image url="https://login.salesforce.com/img/logo190.png" onclick="methodInJavaScript();"/>
<apex:actionFunction name="callControllerMethod" action="{!methodInApex}"/>
</apex:form>
<script>
function methodInJavaScript(){
alert('Hi');
callControllerMethod();
}
</script>
</apex:page>
Point 1 : Use actionFunction when you need to do some extra processing in javascript. For example on click of an image, we need to show a confirmation box asking
user for a Yes or No. Based on users response, we need to call different apex methods.
Point 2 : Use actionFunction when a common apex method needs to be called irrespective of the event originator. For example, we have 5 command buttons on a page. On
click on any of the button, we need to call the same apex function. So instead of writing 5 actionSupport for 5 buttons, write a single actionFunction for all of
them.
Hope this gives you a clear understanding about the usage of actionSupport and actionFunction. Happy learning :)
Comments
Post a Comment