Showing posts with label Visualforce Action Function. Show all posts
Showing posts with label Visualforce Action Function. Show all posts

Wednesday, July 30, 2014

Visualforce Action Function Example.

Visualforce Action Function Example.


Hi, 
In this post i am giving an example of simple usage of <apex:actionFunction> tag in visualforce page to call a apex method from Java script.

Controller Class:


public class ActionFunctionCLS {
  public Account actObj{get;set;}
   PageReference prf= null;
    public ActionFunctionCLS(){
      actObj = new Account();
    }
 
   
    public pagereference Saverec(){
   if(actobj.Name !=''){
    insert actobj;
   
   }
   else{
     ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: Please Enter Name.');
     ApexPages.addMessage(myMsg);
   
   }
   if(actobj.id !=null){
  
      // Send the user to the detail page for the new account.
      prf = new PageReference('/'+actobj.id);
      prf.setRedirect(true);
   
   }
   return prf;
    }

}


Visualforce Page:

<apex:page controller="ActionFunctionCLS" id="pg" >
  <script>
   function recSave(){
    var accountType = document.getElementById('pg:fm:pb:pbs:actType').value;
    alert('accountType -->'+accountType);
    if(accountType != 'Prospect'){
     alert('You Should Select Prospect to Save the Record');
     return false;
    }
    else{
     saveAccount(); //this is the function name which calls our action function from java Script.
     return true;
    }
   }
 
  </script> 

 <apex:form id="fm">
  <apex:actionfunction name="saveAccount" action="{!Saverec}" />
   <apex:pageBlock id="pb">
     <apex:pagemessages ></apex:pagemessages>
     <apex:pageblockButtons >
      <apex:commandButton value="Save" onclick="recSave();return false;"/>    
     </apex:pageblockButtons>
    
     <apex:pageblockSection id="pbs">
       <apex:inputField value="{!actobj.Name}" id="actName"/>
       <apex:inputField value="{!actobj.type}" id="actType"/>
     </apex:pageblockSection>
   </apex:pageBlock>
 </apex:form>
</apex:page>





              




Once you select Account Type as "Prospect" Javascript method will call the <apex:actionfunction name="saveAccount" action="{!Saverec}" /> and controller method is going to execute.



That's it..


 
| ,