Category Archives: Salesforce

How to Use Action Function in Visualforce Page?

ActionFunction is used to execute a method in your Apex Class from your Visualforce Page asynchronously via AJAX requests. Its easy to call a controller method using attribute action="{!YourMethodeName}". An component must be a child of an component. In this article I will demonstrate, how to use actionfunction in visualforce page.

Note: Beginning with API version 23 you can’t place apex:actionFunction inside an iteration component — apex:pageBlockTable, apex:repeat, and so on. Put the apex:actionFunction after the iteration component, and inside the iteration put a normal JavaScript function that calls it.

public with sharing class ActionFunctionTest
{
      public String ReturnValue {get;set;}
      public String FirstName {get;set;}
      public String LastName {get;set;}
    
      public void Result()
      {
          ReturnValue = 'My name is : ' + FirstName +' '+ LastName ;
      }
}

In above class, the variables “FirstName” and “LastName” are the parameters supplied by the javascript and variable “ReturnValue” will display the result.

<apex:page controller="ActionFunctionTest">
<apex:form id="TestFrm">
First Name : 
<apex:inputtext id="txtFirstName" required="true">
Last Name : 
<apex:inputtext id="txtLastName" required="true">
<span class="btn" onclick="return GetMyName()"> Get My Name </span>
<apex:outputpanel id="resultPanel">
<apex:actionstatus id="TestStatus" starttext="Processing..." stoptext="">
<b><apex:outputlabel value="{!ReturnValue}"></apex:outputlabel></b>
</apex:actionstatus></apex:outputpanel>
<apex:actionfunction action="{!Result}" name="TestAF" rerender="resultPanel" status="TestStatus">
<apex:param assignto="{!FirstName}" name="FirstParameter" value="">
<apex:param assignto="{!LastName}" name="SecondParameter" value="">
</apex:param></apex:param></apex:actionfunction>
</apex:inputtext></apex:inputtext></apex:form>
 
<script type="text/javascript">
function GetMyName()
{
var FirstNameValue = document.getElementById("{!$Component.TestFrm.txtFirstName}").value;
var LastNameValue = document.getElementById("{!$Component.TestFrm.txtLastName}").value;
if(FirstNameValue == '' || LastNameValue == '')
{
alert('Please enter your first name and last name');
return false;
}
TestAF(FirstNameValue ,LastNameValue );
return true;
}
</script>
</apex:page>

The below code is used to define the “actionFunction” in visual force page. To send the parameter, we have to use “apex:param” tag. Attribute “assignTo” will assign the parameter to variable name specified in Apex code. Here we have assigned the value to variable “FirstName” and “LastName”.

<apex:actionfunction action="{!Result}" name="TestAF" rerender="resultPanel" status="TestStatus">
<apex:param assignto="{!FirstName}" name="FirstParameter" value="">
<apex:param assignto="{!LastName}" name="SecondParameter" value="">
</apex:param></apex:param></apex:actionfunction>

The resulting JavaScript function created by the visualforce will be “TestAF” because we have set that name for the “apex:actionFunction”. Actionfunction’s attribute “action” will call the method “Result” which is specified in Apex class “ActionFunctionTest” and “status” will show the Ajax request status. Below JavaScript method is used to call the generated method by “apex:actionFunction”.

<script type="text/javascript">
  function GetMyName()
  {
   var FirstNameValue = document.getElementById("{!$Component.TestFrm.txtFirstName}").value;
   var LastNameValue = document.getElementById("{!$Component.TestFrm.txtLastName}").value;
   if(FirstNameValue == '' || LastNameValue == '')
   {
    alert('Please enter your first name and last name');
    return false;
   }
   TestAF(FirstNameValue ,LastNameValue );
   return true;
  }
 </script> 

1

2

3

4

Links in Visualforce Page pageblocktables

<apex:pageblocktable value="{!FindContact}" var="item">
<apex:column headervalue="Name">
<apex:outputlink value="/{!item.id}">
<apex:outputtext value="{!item.Name}"></apex:outputtext>
</apex:outputlink>
</apex:column>
<apex:column headervalue="Email" value="{!item.Email}"></apex:column>
<apex:column headervalue="Phone" value="{!item.Phone}"></apex:column>
<apex:column headervalue="Birthdate" value="{!item.Birthdate}"></apex:column>
</apex:pageblocktable>

Bypass Salesforce Duplicate Rule in Apex Class

Sample Code:

Database.DMLOptions dbDML = new Database.DMLOptions(); 
dbDML.DuplicateRuleHeader.allowSave = true;
dbDML.DuplicateRuleHeader.runAsCurrentUser = true;
Account duplicateAcc = new Account(Name='Salesforce');
Database.SaveResult sr = Database.insert(duplicateAcc, dbDML);
if (sr.isSuccess()) {
    System.debug('Duplicate account has been inserted in Salesforce!');
}

APIs in Salesforce

API Name Protocol Data Format Communication
REST API REST JSON, XML Synchronous
SOAP API SOAP (WSDL) XML Synchronous
Chatter REST API REST JSON, XML Synchronous (photos are processed
asynchronously)
User Interface API REST JSON Synchronous
Analytics REST API REST JSON, XML Synchronous
Bulk API REST CSV, JSON, XML Asynchronous
Metadata API SOAP (WSDL) XML Asynchronous
Streaming API Bayeux JSON Asynchronous (stream of data)
Apex REST API REST JSON, XML, Custom Synchronous
Apex SOAP API SOAP (WSDL) XML Synchronous
Tooling API REST or SOAP (WSDL) JSON, XML, Custom Synchronous

Data Import From CSV Using Visualforce Page

Sometimes we need to read a CSV file in a Visualforce Page. Here is an example to read a CSV file and display it in Visualforce Page. Below example reads a CSV file having Account records in it and displays them in a table.

CSV file format used in this example:

Controller:

Public with sharing class Sample {
    
    public Blob csvFileBody {get;set;}
    Public string csvAsString {get;set;}
    Public String[] csvFileLines {get;set;}
    Public String[] inputValues {get;set;}
    Public List<string> fieldList {get;set;}
    Public List<account> sObjectList {get;set;}
    
    public Sample(){
        csvFileLines = new String[]{};
            fieldList = New List<string>();
        sObjectList = New List<sObject>(); 
    }
    
    Public void readcsvFile(){
        csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n');
        inputValues = new String[]{};
            
            for(string st:csvfilelines[0].split(',')){
                fieldList.add(st); 
            }
        
        for(Integer i=1; i<csvfilelines.size(); i++){
            Account accRec = new Account() ;
            string[] csvRecordData = csvFileLines[i].split(',');
            accRec.Name = csvRecordData[0] ;             
            accRec.AccountNumber = csvRecordData[1];
            accRec.Type = csvRecordData[2];
            accRec.Industry = csvRecordData[3];                                                                               
            sObjectList.add(accRec);   
        }
    }
}

Visualforce Page:

<apex:page controller="Sample">
    <apex:form>
        <apex:pageBlock>
            <apex:panelGrid columns="2"> 
                <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                <apex:commandButton value="Read CSV" action="{!readcsvFile}"/>
            </apex:panelGrid>
        </apex:pageBlock>
        <apex:pageBlock>
            <apex:pageblocktable value="{!sObjectList}" var="rec">
                <apex:column value="{!rec.Name}" />
                <apex:column value="{!rec.AccountNumber}"/>
                <apex:column value="{!rec.Type}" />
                <apex:column value="{!rec.Industry}" />
            </apex:pageblocktable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output: