Wednesday, June 28, 2017

Visual force Actions in salesforce:

apex:actionFunction

A component that provides support for invoking controller action methods directly from JavaScript code using an AJAX request. An <apex:actionFunction> component must be a child of an <apex:form> component.
Diff <apex:actionSupport>, which only provides 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.

How can you call a controller method from JavaScript?

To call a controller method (Apex function) from JavaScript, you need to use actionfunction.
Look at the below piece of code to understand how a controller method is called using actionfunction.


1

2

3

4

5

6

7

8

9

10

11
<apex: page>
<apex:form id ="frm">
<apex:actionfunction name="callfromJS" action="{!controllerMethodName} reRender="frm"/>

</apex:form>
<script>
function JSmethodCallFromAnyAction()
{
callfromJS();
}
</apex:page>

This tag supports following attributes:

Attribute
Description
action
The action method invoked when the actionFunction is called by a JavaScript event elsewhere in the page markup. Use merge-field syntax to reference the method. For example, action="{!save}" references the save method in the controller. If an action is not specified, the page simply refreshes.
focus
The ID of the component that is in focus after the AJAX request completes.
id
An identifier that allows the actionFunction component to be referenced by other components in the page.
immediate
A Boolean value that specifies whether the action associated with this component should happen immediately, without processing any validation rules associated with the fields on the page. If set to true, the action happens immediately and validation rules are skipped. If not specified, this value defaults to false.
name
The name of the JavaScript function that, when invoked elsewhere in the page markup, causes the method specified by the action attribute to execute. When the action method completes, the components specified by the reRender attribute are refreshed.
onbeforedomupdate
The JavaScript invoked when the onbeforedomupdate event occurs--that is, when the AJAX request has been processed, but before the browser's DOM is updated.
oncomplete
The JavaScript invoked when the result of an AJAX update request completes on the client.
rendered
A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true.
reRender
The ID of one or more components that are redrawn when the result of the action method returns to the client. This value can be a single ID, a comma-separated list of IDs, or a merge field expression for a list or collection of IDs.
status
The ID of an associated component that displays the status of an AJAX update request. See the actionStatus component.
timeout
The amount of time (in milliseconds) before an AJAX update request should time out.


Visualforce Example:

<apex:page controller="exampleCon">
    <apex:form >
        <!-- Define the JavaScript function sayHello-->
        <apex:actionFunction name="sayHello" action="{!sayHello}" rerender="out" status="myStatus"/>
    </apex:form>
     <apex:outputPanel id="out">
    <apex:outputText value="Hello "/>
    <apex:actionStatus startText="requesting..." id="myStatus">
        <apex:facet name="stop"> {!username}</apex:facet>
    </apex:actionStatus>
    </apex:outputPanel>
             
    <!-- Call the sayHello JavaScript function using a script element-->
    <script>window.setTimeout(sayHello,5000)</script>
             
    <p><apex:outputText value="Clicked? {!state}" id="showstate" /></p>
             
    <!-- Add the onclick event listener to a panel. When clicked, the panel triggers
    the methodOneInJavascript actionFunction with a param -->
    <apex:outputPanel onclick="methodOneInJavascript('Yes!')" styleClass="btn">
        Click Me
    </apex:outputPanel>
    <apex:form >
  
    <apex:actionFunction action="{!methodOne}" name="methodOneInJavascript" rerender="showstate">
        <apex:param name="firstParam" assignTo="{!state}" value="" />
    </apex:actionFunction>
    </apex:form>
</apex:page>

Controller class:

public class exampleCon {
    String uname;
   private String state = 'no';
  
    public String getUsername() {
        return uname;
    }
             
    public PageReference sayHello() {
        uname = UserInfo.getName();
        return null;
    }
             
    public void setState(String n) {
        state = n;
    }
             
    public String getState() {
        return state;
    }
             
    public PageReference methodOne() {
        return null;
    }
}




save image

What is Difference between action support and action function 

1. Both action support and function can be used to call a controller method using an AJAX request.
  • for example call controller onclick of a inputcheck box
  • or call a controller method onfocus of a input field
Well, they both do the same thing of calling controller method.

Difference between both:

1. Action function can call the controller method from java script.
2. Action support adds AJAX support to another visualforce component and then call the controller method.
    for example:

<apex:outputpanel id="outptpnl">
             <apex:outputText value="click here"/>
         <apex:actionSupport event="onclick" action="{!controllerMethodName}"  rerender="pgblck" />
     </apex:outputpanel>



Here action support adds AJAX to output panel, so once you click on output panel controller method will be called.

3. Action function cannot add AJAX support to another component. But from a particular component which has AJAX support(onclick, onblur etc) action function can be called to call the controller method.
Example:

 <apex:actionFunction name="myactionfun"  action="{!actionFunMethod}" reRender="outptText"/> <apex:inputcheckbox onclick="myactionfun" />


In this example onlick of input checkbox "myactionfun" action function is called from where controller method "actionFunMethod" gets called.
Apart from this, the main difference between the "two" action support and action function is that, the action function can also be called from java script.Example:

<apex:actionFunction name="myactionfun"  action="{!actionFunMethod}" reRender="outptText"/>
 <apex:inputcheckbox onclick="myJavaMethod()" />
<script>
   function myJavaMethod(){
     myactionfun();// this call the action function
  }
  </script>


Here onclick of the inputcheck box java script is called from where the action function gets called and ultimately your controller method.

Lets demo both as a full fledged example:

Click in the Input text to call controller method using action support
Click the input check box to call Java script, then confirm in java script, upon confirmation controller method is called using action function.

Tex in the lower pageblock gets changed depending on whether the controller method is called by action support or action function.




Controller Class :

public class ActionSupController {

Public string Display_This_String{get;set;}
    Public ActionSupController(){
     Display_This_String = 'value set in constructor';
    }
   
    Public void actionFunMethod(){
      Display_This_String = 'value set in action function method';
    }
   
    Public void actionSupMethod(){
      Display_This_String = 'value set in action Support method';
    }

}

Visualforce Page: 

<apex:page controller="ActionSupController">
 <apex:form >
  <h1>Demonstration of difference between Action function and Action Support</h1>

  <apex:actionFunction name="myactionfun"  action="{!actionFunMethod}" reRender="outptText"/><br></br> <br></br>

  Input Text <apex:inputText >
                <apex:actionSupport action="{!actionSupMethod}" event="onclick" reRender="outptText" />
             </apex:inputText> <br></br>
            
Click me to call action function method   <apex:inputcheckbox onclick="myJavaMethod()" /><br></br> <br></br>  
    <apex:pageBlock >
        <apex:outputText value="{!Display_This_String}" id="outptText"/>
    </apex:pageBlock>        

  <script>
   function myJavaMethod(){
   var checkinput = confirm('Are sure you wnat to call action function method?');
   if(checkinput == true)
      myactionfun();
  }
  </script>
 </apex:form> 

 </apex:page>

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.

What is Action Function in Salesforce?


Its easy to call a controller method for most of the attributes using action="{!Yourmethode_Name}", but what if you were to call the controller method from java script?

One way to do this is by using Action Function. Expertise will definitely be able to use this in complex scenarios. This post is for those who haven't had hands on action function before and want to know how to use it.

Lets take a Example and work on it:


You have a checkbox and you are calling javascript function on click of this checkbox. And now once you are in js you wish to modify some variable or do something in your controller class.

Say you want to put some value for a variable in controller and then display it on your page. this will require calling your class method from js.


Example :

Visualforce Page:

<apex:page standardcontroller="Account" extensions="ActionFunctionController" tabStyle="Account">
    <apex:form >
       <apex:actionFunction name="actionFunName" action="{!ActionFunMethode}" reRender="outputtxtId"/>
       <apex:pageBlock > 
            <apex:outputLabel for="inptCheckBox" value="Check this box to call Controller method from js using ActionFunction" style="color:green;"></apex:outputLabel> 
            <apex:inputcheckbox onclick="javaScrpt()" id="inptCheckBox"/>
       </apex:pageBlock> 
      
      <apex:outputText value="{!MyString_From_Methode}" id="outputtxtId"></apex:outputText> 
    </apex:form> 
    
    <script>
      function javaScrpt(){
       actionFunName(); 
      }
    </script>
     

</apex:page>


Controller class:

Public class ActionFunctionController {
Public string MyString_From_Methode{get;set;}

  public ActionFunctionController(ApexPages.StandardController controller) {

    }

  public string ActionFunMethode(){
     MyString_From_Methode = 'Method called from js using Action function';
     return null;
    }

}



Output:
save image


save image

How to Pass Parameters in Action Function 

We can pass parameters to controller method that is being called using action function. For this we can use attribute "param" in visualforce.



Following is an example to demonstrate the parameter passing using param in action function. Clicking the checkbox calls the controller method using action function, first name and last name are passed to the controller using param attribute

Visualforce Page:

<apex:page controller="passparam">
 <apex:form>
  <apex:pageblock id="pgblck">
   First name : <apex:inputtext id="fn" value="{!firstname}">
   Last Name :<apex:inputtext id="ln" value="{!lastname}">
 Click this to See fullname :  <apex:inputcheckbox onclick="calculate('{!$Component.fn}','{!$Component.ln}')">
Full Name:    <apex:outputtext value="{!fullname}"></apex:outputtext>
  </apex:inputcheckbox></apex:inputtext></apex:inputtext></apex:pageblock>
<apex:actionfunction action="{!calpercentage}" name="calAF" rerender="pgblck">
<apex:param assignto="{!firstname}" name="param1" value="">
<apex:param assignto="{!lastname}" name="param" value="">
</apex:param></apex:param></apex:actionfunction>
 </apex:form>
 <script>
  function calculate(frst,lst){
  var Fname = document.getElementById(frst).value;
 var Lname = document.getElementById(lst).value;
   var res = confirm('Do you want to calculate?');
   if(res == true)
      calAF(Fname,Lname );
  }
 </script>
</apex:page>


Controller :

Public class passparam{
Public string firstname{get;set;}
Public string lastname{get;set;}
Public string fullname{get;set;}
 Public void calpercentage(){
  fullname = firstname +' '+lastname;
 }
}



Output :


No comments:

Post a Comment