Monday, January 25, 2016

ActionFunction in Visualforce

ActionFunction component provides support for invoking Controller action method directly from JavaScript code using AJAX request. An apex:ActionFunction component must be child of an apex:form component.

ActionFunction component is used hen we want to call a controller method from Javascript.

Where as Apex ActionSupport - which only provide support for invoking controller action methods from other Visualforce components, <apex:actionFunction> defines a new JavaScript function which can then be called from within a block of JavaScript code.

Example of using Action function.

Controller -

 public class AccountActionFunction {  
   public Account acc{get;set;}  
   public boolean showfname{get;set;}  
   public boolean showlname{get;set;}  
   public boolean showWebAddr{get;set;}  
   public AccountActionFunction() {  
     System.debug('###Inside Constructor');  
     acc = new Account();  
     showfname = false;  
     showlname = false;  
     showWebAddr = false;  
   }  
   public PageReference AccountTypeChange() {  
     System.debug('$$$- Inside AccountTypeChange()');  
     if(acc.Account_Type__c == 'Person') {  
       showfname = true;  
       showlname = true;  
     } else if(acc.Account_Type__c == 'Company') {  
       showWebAddr = true;  
     } else {  
       showfname = false;  
       showlname = false;  
       showWebAddr = false;  
     }  
     return null;  
   }  
   public String getAccounts() {  
     System.debug('@@@ insite getAccounts()');  
     return null;  
   }  
 }  
Visualforce Page -
 <apex:page controller="AccountActionFunction" tabStyle="Account" action="{!getAccounts}">  
   <apex:form >  
     <apex:actionFunction name="AccountTypeJS" action="{!AccountTypeChange}" reRender="typePB"/>  
     <apex:pageBlock >  
       <apex:pageBlockSection title="Select Account type for Different fields" columns="2" id="typePB" collapsible="false">  
         <apex:inputField value="{!acc.Account_Type__c}" onchange="AccountTypeJS()"/>  
         <apex:inputField value="{!acc.First_Name__c}" rendered="{!showfname}"/>  
         <apex:inputField value="{!acc.Last_Name__c}" rendered="{!showlname}"/>  
         <apex:inputField value="{!acc.Web_Address__c}" rendered="{!showWebAddr}"/>  
       </apex:pageBlockSection>  
     </apex:pageBlock>  
   </apex:form>  
 </apex:page>  
 

No comments:

Post a Comment