Wednesday, July 30, 2014

Visualforce Action Function Example.

Visualforce Action Function Example.

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;
     ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: Please Enter Name.');
   if( !=null){
      // Send the user to the detail page for the new account.
      prf = new PageReference('/';
   return prf;


Visualforce Page:

<apex:page controller="ActionFunctionCLS" id="pg" >
   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;
     saveAccount(); //this is the function name which calls our action function from java Script.
     return true;

 <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:pageblockSection id="pbs">
       <apex:inputField value="{!actobj.Name}" id="actName"/>
       <apex:inputField value="{!actobj.type}" id="actType"/>


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..


vasudha dharani said...

Salesforce Admin Corporate Training | Online Training by real time Experts with IT Support IND: 910-0934572. Online Training classes gives you complete knowledge by 21st Century. send ur enquiry to or Call +917386622889 Salesforce Admin Training| USA:201-210-8616|Online/Corporate training|21cssindia 

Archita Patnaik said...

hey, can you help me regarding the issues, i found during executing this code:-
Its not inserting any record , it just reload same vf page.

Anonymous said...

thanx for such useful post..

Siva P said...

why return false in onclick event, can you please explain?

ankit said...

Can you please let me know the uses of actionfunction

Unknown said...

Very Neat Explaination. Thank you !

JIMY said...

thank you....

Server and storage

Server and Storage Solutions

Post a Comment

| ,