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


Post a Comment

| ,