Wednesday, December 31, 2014

Adding and Deleting rows dynamically in pageblock table in Visualforce page.

Adding rows dynamically in pageblock table in Visualforce page.


Hi, 

In this post i am going to give sample example of how to add a row dynamically in pageblock table and how to remove the row from pageblock table dynamically.

For this i am developed one Visualforce page, One Controller and One Helper class. Initially i am loading the page with one row then after once the user clicks on AddRow button it is going to add 
one new row to that pagblock table. If you want to remove a particular row you can remove using Remove row link.



Visualforce Page:

<apex:page controller="AddMultipleAccountCLS">
<apex:form id="theForm">
 <apex:pageblock id="thePB" title="Creating Multiple Accounts">
  <apex:pageblockButtons >
   <apex:commandButton value="Save" action="{!SaveMultipleAccounts}"/>
  
  </apex:pageblockButtons>

  <apex:outputPanel id="accountHead">
  <apex:variable value="{!0}" var="rowNum"/>  
   <apex:pageBlockSection columns="1" title="Adding Multiple Accounts" id="thePbs" collapsible="False"> 
   
     <apex:pageBlockTable value="{!waAccList}" var="eachRecord"> 
      
      <apex:column headerValue="Action">
        <apex:commandLink value="Remove" style="color:red" action="{!removeRowFromAccList}" rendered="{!rowNum > 0}" rerender="accountHead" immediate="true" >
             <apex:param value="{!rowNum}" name="rowToRemove" assignTo="{!rowToRemove}"/>
         </apex:commandLink>
         <apex:variable var="rowNum" value="{!rowNum + 1}"/>
      </apex:column>
      
      <apex:column headerValue="Account Name">
                            <apex:inputField value="{!eachRecord.record.Name}" required="true"/>
       </apex:column>
      
      <apex:column headerValue="Account Number">
                            <apex:inputField value="{!eachRecord.record.AccountNumber}" required="true"/>
       </apex:column>
       
       
       <apex:column headerValue="Account Type">
                                <apex:inputfield value="{!eachRecord.record.Type}" required="true"/>
        </apex:column>
      
      <apex:column headerValue="Annual Revenue">
                                <apex:inputField value="{!eachRecord.record.AnnualRevenue}" required="true"/>
      </apex:column>   
    
    </apex:pageBlockTable>
   </apex:pageBlockSection>
   <apex:commandButton value="Add More" action="{!addNewRowToAccList}" rerender="accountHead" Status="status" immediate="true" />
   
  </apex:outputPanel>

 </apex:pageblock>
</apex:form>
  
</apex:page>

Controller Class:


public with sharing class AddMultipleAccountCLS {

    public PageReference SaveMultipleAccounts() {
    system.debug('controller save method is calling-->');
     AddMultipleAccountHelperCLS.save(waAccList);
    return null;
    }


 public List<WrapperpaAccountList> waAccList {get;set;}
 public Integer rowToRemove {get;set;}

 public AddMultipleAccountCLS(){
  waAccList = new List<WrapperpaAccountList>();
  addNewRowToAccList();
 }
 public void removeRowFromAccList(){
  waAccList = AddMultipleAccountHelperCLS.removeRowToAccountList(rowToRemove, waAccList);
   
 }

 public void addNewRowToAccList(){
     waAccList = AddMultipleAccountHelperCLS.addNewRowToAccList(waAccList);
    }
    
    

 public class WrapperpaAccountList{
        public Integer index {get;set;}
        public Account record {get;set;}
   } 
}


Controller Helper Class:

public class AddMultipleAccountHelperCLS {

    public static List<AddMultipleAccountCLS.WrapperpaAccountList> addNewRowToAccList(List<AddMultipleAccountCLS.WrapperpaAccountList> waAccObjList){
        AddMultipleAccountCLS.WrapperpaAccountList newRecord = new AddMultipleAccountCLS.WrapperpaAccountList();
        Account newAccountRecord = new Account();        
        newRecord.record = newAccountRecord;
        newRecord.index = waAccObjList.size();
        waAccObjList.add(newRecord);
        return waAccObjList;
    }
    
    
     public static List<AddMultipleAccountCLS.WrapperpaAccountList> removeRowToAccountList(Integer rowToRemove, List<AddMultipleAccountCLS.WrapperpaAccountList> waAccountList){
        waAccountList.remove(rowToRemove);
        return waAccountList;
    }
    
    public static void save(List<AddMultipleAccountCLS.WrapperpaAccountList> waAccList) {
        system.debug('==waAccList==>'+waAccList.size());
        List<Account> accountRecordsToBeInserted = new List<Account>();
        if(waAccList !=null && !waAccList.isEmpty()){
            for(AddMultipleAccountCLS.WrapperpaAccountList eachRecord : waAccList ){
                Account accTemp = eachRecord.record;
                accountRecordsToBeInserted.add(accTemp);
               
            }
            system.debug('==accountRecordsToBeInserted==>'+accountRecordsToBeInserted.size());
            insert accountRecordsToBeInserted;
        }
    }
}



This is about Dynamic row adding and Deleting functionality in Page Block table using Visualforce Tags.


Thanks..












Tuesday, December 30, 2014

How to create Visualforce Tabs in Salsforce and Create Account,Contact,Opportunity record at once using Visualforce page?

How to create Visualforce Tabs in Salsforce and Create Account,Contact,Opportunity record at once using Visualforce page?


Hi,
In this post i am going to give idea on how to create visualforce tabs, how to use JavaScript for validation in VF page and how to assign different colors to each pageblock section in visualforce, for that,

I created a VF page with Custom Controller to read the Account,Contact,Opportunity to save all the three object details once with JavaScript validatons.

Setup-->Create-->Tabs-->Click on New (Visualforce Tabs) Section-->Enter the Tab Label and Name of the Tab--> Select the VF page-->Tab Style--> Save




once you done this process it is available in tabs..

Visualforce Page:

<apex:page controller="AccountToOpportunityFlow" title="Opportunity">
<script type="text/javaScript">
function colorPageBlock(pageblock, color) {
if (pageblock != null) pageblock.firstChild.style.cssText = "background-color: " + color + ";";

}

function validateValues(){
alert('validateValues');
var status= true;

var accName = document.getElementById('{!$Component.theform.thePB.theacc.accName}').value;
var conLastName = document.getElementById('{!$Component.theform.thePB.theCon.conLastName}').value;
var oppName = document.getElementById('{!$Component.theform.thePB.theOpp.oppName}').value;
var oppCloseDate = document.getElementById('{!$Component.theform.thePB.theOpp.oppcloseDate}').value;
var oppStage = document.getElementById('{!$Component.theform.thePB.theOpp.oppStage}').value;

//alert('accName = '+accName);
if(accName =='' || accName ==null){
alert("Account Name Should Not be Empty.");
return false
}

else if(conLastName =='' || conLastName == null){
alert("Contact Last Name should not be Empty.");
return false
}

else if(oppName == '' || oppName ==null){
alert("Opportunity Name should not be Empty.");
return false
}

else if(oppCloseDate == '' || oppCloseDate ==null){
alert("Opportunity CloseDate should not be Empty.");
return false
}

else if(oppStage == '' || oppStage ==null){
alert("Please Select Opportunity Stage Details.");
return false
}

/*
//alert('status is==>'+status);
if(status){
 return true;
}
else{
  return false;
}
 */
}

</script>

<apex:sectionHeader title="New Account To Opportunity" subtitle=""/>
<apex:form id="theform">
<apex:pageblock title="Account Details" id="thePB">
<apex:pageBlockButtons >
 <apex:commandButton value="Save" onclick="return validateValues();" action="{!Save}"/>
 <apex:commandButton value="Cancel" action="{!Cancel}" immediate="true"/>
</apex:pageBlockButtons>


 <apex:pageBlockSection title="Account Information" collapsible="false" columns="2" id="theacc" >
 <apex:inputField value="{!acc.name}" id="accName"/>
  <apex:inputField value="{!acc.AccountNumber}"/>
 <apex:inputField value="{!acc.AccountSource}"/>
  <apex:inputField value="{!acc.Phone}"/>
  <apex:inputField value="{!acc.Fax}"/>
  <apex:inputField value="{!acc.Website}"/>
 </apex:pageBlockSection>


 <apex:pageblockSection title="Contact Information" collapsible="false" columns="2" id="theCon">  
  <apex:inputField value="{!con.FirstName}" />
  <apex:inputField value="{!con.LastName}" id="conLastName"/>
  <apex:inputField value="{!con.Email}"/>
  <apex:inputField value="{!con.Phone}"/> 
  <apex:inputField value="{!con.mobilePhone}"/>  
  <script>colorPageBlock(document.getElementById("{!$Component.theCon}"), "red");</script>
 </apex:pageblockSection>

 <!--Opportunity Details -->
 <apex:pageblockSection title="Opportunity Information" collapsible="false" columns="2" id="theOpp">
  <apex:inputField value="{!opp.Name}" id="oppName"  />
  <apex:inputField value="{!opp.CloseDate}" id="oppcloseDate"/>
  <apex:inputField value="{!opp.StageName}" id="oppStage"/>
  <apex:inputField value="{!opp.leadSource}"/> 
  
                
  <script>colorPageBlock(document.getElementById("{!$Component.theOpp}"), "Yellow");</script>
 </apex:pageBlockSection>


</apex:pageblock>
</apex:form>  

</apex:page>


Controller Class:

public class AccountToOpportunityFlow {

 public Account acc{get;set;}
 public Contact con {get;set;}
 public Opportunity opp{get;set;}

 public AccountToOpportunityFlow(){
  acc= new Account();
  con = new Contact();
  opp = new Opportunity();

 }

  public PageReference Cancel() {
    PageReference accOppPage = new PageReference('/apex/accountToOpportunityFlow');
    accOppPage.setRedirect(true);
    return accOppPage; 
  }


    public PageReference Save(){
     try{
      if(acc.Name !=null && acc.Name !=''){
        insert acc;
       }
       if(acc.id !=null && con.LastName !=null && con.lastName !=''){
         con.AccountId = acc.id;
         insert con;
       }
       if(acc.id !=null && opp.name !=null && opp.name !=''){
         opp.AccountId = acc.id;
        insert opp;
       }       
     
     }Catch(Exception e){
      system.debug('Exception occurred...'+e);
     }
      
     return null;
    }


}






Note: If you observe carefully of pageblock section each section with different colors, to achieve this i changed the background color from JavaScript.





Sunday, December 28, 2014

Custom Controller Pagination with dynamic search.

Custom Controller Pagination with dynamic search in Visualforce page.


Hi,

In this post i am going to give a small example on how to use dynamic search in visualforce with pagination using custom controller.


For this once the user enter his search criteria and click on search button the page is going to populate account details with Pagination of (Next,Previous,Last etc..). To achieve this i am using custom controller instead of Standared Set Controller.


Pagination in Visualforce



Visualforce Page:

<apex:page controller="AccountMultipleSearchWithPagenationCLS" action="{!searchAcc}" >
<script type="text/javascript">
    window.onload=function() {
    // document.getElementById("{!$Component.thePb.thepbs.accName}").focus();
    }   
</script>
 <apex:form >
  <apex:pageBlock id="thePb" title="Account Details To Search">
   <apex:pageblockSection id="thepbs">
    <apex:inputField value="{!acc.Created_From_Date__c}" />
     <apex:inputField value="{!acc.Created_To_Date__c}"/>
     <apex:inputField value="{!acc.Name}" required="false" id="accName"/>
     <apex:inputfield value="{!acc.accountNumber}"/>
   </apex:pageblockSection>
   <apex:pageblockButtons location="bottom">
      <apex:commandButton value="Search" action="{!searchAcc}" />
     </apex:pageblockButtons>  
  </apex:pageBlock>
  
   <apex:pageBlock title="Account Details" id="noRec" rendered="{! IF( accountList != null && accountList.size ==0 , true, false)}" >
  <apex:outputPanel >
    <h1>No Records Found </h1>
</apex:outputPanel>
  </apex:pageBlock>

  
  <apex:pageBlock title="Account Details" id="details" rendered="{! IF( accountList != null && accountList.size >0, true, false)}" >

   <apex:pageBlockTable value="{!accountList}" var="a">
   <apex:column headerValue="Account Name">
    <apex:outputLink target="_blank" value="/{!a.id}">{!a.Name}</apex:outputLink> 
   </apex:column>   
    <!--  If you want facet style you can add like this.
   <apex:column >
     <apex:facet name="header">Link Name</apex:facet>
     <apex:outputLink target="_blank" value="/{!a.id}">{!a.Name}</apex:outputLink> 
    </apex:column>
    -->
    <apex:column value="{!a.accountNumber}" headerValue="Account Number"/>  
    <apex:column value="{!a.Industry}" headerValue="Industry"/>  
    <apex:column value="{!a.AnnualRevenue}" headerValue="Annual Revenue"/>  
  <apex:column value="{!a.Phone}" headerValue="Phone"/>   
  <apex:column value="{!a.website}" headerValue="Web"/>    
   </apex:pageBlockTable>
   
    <apex:pageblockButtons >
 <apex:commandButton value="First Page" rerender="details" action="{!FirstPage}" disabled="{!prev}"/>
<apex:commandButton value="Previous" rerender="details" action="{!previous}" disabled="{!prev}"/>
<apex:commandButton value="Next" rerender="details" action="{!next}" disabled="{!nxt}"/>
<apex:commandButton value="Last Page" rerender="details" action="{!LastPage}" disabled="{!nxt}"/>
</apex:pageblockButtons>
   
  </apex:pageBlock>

 </apex:form>
</apex:page>


Controller Class:

public with sharing class AccountMultipleSearchWithPagenationCLS {
public Account acc{get;set;}
public List<Account> accountList {get;set;}
// create a list of strings to hold the conditions
List<string> conditions = new List<string>();
private integer totalRecs = 0;
private integer OffsetSize = 0;
private integer LimitSize= 10;

public AccountMultipleSearchWithPagenationCLS(){
system.debug('==>AccountMultipleSearchWithPagenationCLS  is calling==>');
 acc = new Account();
 //accountList  = new List<Account>();
}

public void searchAcc(){
totalRecs = 0;
OffsetSize = 0;
if(accountList !=null && accountList.size()>0){
 accountList=null;
}
searchAccounts ();
conditions.clear();
}


public Void searchAccounts(){

System.debug('Total Records is ==>'+totalRecs);
System.debug('OffsetSize is ==>'+OffsetSize);

if(accountList != null && !accountList.isEmpty()){
  accountList.clear();
}
 String strQuery ='SELECT Id,Name,AccountNumber,CreatedDate,Phone,Website,Industry,AnnualRevenue From Account';
 if(acc.Created_From_Date__c !=null){
  String fromDate = acc.Created_From_Date__c+'';
  fromDate = fromDate.split(' ',0)[0]+'T00:00:00.000Z';
   conditions.add('CreatedDate >='+fromDate);
 }

if(acc.Created_To_Date__c !=null){
 String toDate = acc.Created_To_Date__c+'';
  toDate = toDate.split(' ',0)[0]+'T23:59:59.000Z';
   conditions.add('createdDate <='+toDate);
 }

 if(acc.Name !=null && acc.Name !=''){
   conditions.add('Name Like \'%' +acc.Name +'%\' ');
 }
  if(acc.AccountNumber !=null && acc.AccountNumber !=''){
   conditions.add('AccountNumber Like\'%' +acc.AccountNumber +'%\' ');
 }

  if (conditions.size() > 0) {
   strQuery += '  WHERE ' + conditions[0];
   for (Integer i = 1; i < conditions.size(); i++)
            strQuery += '  AND ' + conditions[i];
  }
 if(totalRecs !=null && totalRecs ==0){
    List<Account> accTemp = Database.query(strQuery);
    totalRecs = (accTemp !=null &&accTemp.size()>0)?accTemp.size():0;
 }

 system.debug('strQuery ==>'+strQuery );
 // add sort and limits at the end  
  strQuery += ' ORDER BY Name  ASC, CreatedDate DESC LIMIT :LimitSize OFFSET :OffsetSize';
  
  accountList  =Database.query(strQuery);
  
   

  //conditions.clear();
  //return accountList.size();
}

public void FirstPage()
{
OffsetSize = 0;
searchAccounts();
}
public void previous()
{
OffsetSize = (OffsetSize-LimitSize);
searchAccounts();
}
public void next()
{
OffsetSize = OffsetSize + LimitSize;
searchAccounts();
}
public void LastPage()
{
OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
searchAccounts();
}
public boolean getprev()
{

if(OffsetSize == 0){

return true;
}
else {

return false;
}
}
public boolean getnxt()
{
if((OffsetSize + LimitSize) > totalRecs){

return true;
}
else {

return false;
}
}


}



Example 2: 


In this example i am not using any buttons simple using command links move forward or backward directions and also displaying the count of records, page numbers etc..




VF Page:
<apex:page controller="CustomPaginationVFController">
          
    <apex:form >
                
        <apex:pageBlock title="VF Sample Custom Pagination Example" id="mpb">
        
            <!-- next, previous and page info -->
            <apex:commandLink action="{!doPrevious}" rendered="{!hasPrevious}" value="Previous" />
            <apex:outputLabel rendered="{!NOT(hasPrevious)}" value="Previous" />
            
            <apex:outputLabel value=" (page {!page} of {!totalPages}) | showing {!startIdx} to {!endIdx} of {!totalRecords} " />
            
            <apex:commandLink action="{!doNext}" rendered="{!hasNext}" value="Next" />
            <apex:outputLabel rendered="{!NOT(hasNext)}" value="Next" />
            
            <br/>
            
            <!-- table of data -->
            <apex:pageBlockTable title="Contacts" value="{!tRecords}" var="c">
                <apex:column >
                    <apex:facet name="header">Action</apex:facet>
                    <apex:inputCheckbox value="{!c.IsSelected}" />
                </apex:column>
                <apex:column value="{!c.tContact.FirstName}"/>
                <apex:column value="{!c.tContact.LastName}"/>
                <apex:column value="{!c.tContact.Title}"/>
                <apex:column value="{!c.tContact.Phone}"/>
                <apex:column value="{!c.tContact.Email}"/>
            </apex:pageBlockTable>
        
            <br/>
            
            <!-- next, previous and page info -->
            <apex:commandLink action="{!doPrevious}" rendered="{!hasPrevious}" value="Previous" />
            <apex:outputLabel rendered="{!NOT(hasPrevious)}" value="Previous" />
            
            <apex:outputLabel value=" (page {!page} of {!totalPages}) | showing {!startIdx} to {!endIdx} of {!totalRecords} " />
            
            <apex:commandLink action="{!doNext}" rendered="{!hasNext}" value="Next" />
            <apex:outputLabel rendered="{!NOT(hasNext)}" value="Next" />
            
        
        </apex:pageBlock> 
        
    </apex:form>



</apex:page>


Controller Class:


public with sharing class CustomPaginationVFController {

    //default page size
    private static final Integer PAGE_SIZE = 10;
    
    
    //pagination information
    public Integer page{get;set;}
    public Integer totalRecords{get;set;}
    public Integer totalPages{get;set;}
    public Integer startIdx{get;set;}
    public Integer endIdx{get;set;}
    
    

    /*
    *   set controller
    */
    public List<CCWRow> tRecords{get;set;}
    
    
    
    /*
    *   constructor
    */
    public CustomPaginationVFController ()
    {
        //init variable
        this.tRecords = new List<CCWRow>();
        
        //set initial page
        this.page = 1;
        
        //load records
        getContacts();
                
    }
    
    
    /*
    *   advance to next page
    */
    public void doNext(){
        
        if(getHasNext()){
            this.page++;
            getContacts();
        }

    }
    
    
    /*
    *   advance to previous page
    */
    public void doPrevious(){
        
        if(getHasPrevious()){
            this.page--;
            getContacts();
        }
                
    }
    
    /*
    *   returns whether the previous page exists
    */
    public Boolean getHasPrevious(){
        if(this.page>1){
            return true;
        }
        else{
            return false;
        }
    }
    
    /*
    *   returns whether the next page exists
    */
    public Boolean getHasNext(){
        if(this.page<this.totalPages){
            return true;
        }
        else{
            return false;
        }
    }
    
    
    
    /*
    *   return current page of records
    */
    public void getContacts(){
        
        //calculate range of records for capture
        this.startIdx = (this.page-1)*PAGE_SIZE;
        this.endIdx = this.page*PAGE_SIZE;
        this.totalRecords = 0;
        
        //clear container for records displayed
        this.tRecords.clear();
                
        
        //cycle through
        for(Contact c : [SELECT Id, FirstName, LastName, Title, Phone, MobilePhone, Email, 
                            MailingStreet, MailingState, MailingPostalCode, MailingCountry, MailingCity 
                            FROM Contact 
                            ORDER BY LastName ASC 
                            LIMIT 50000]){
        
            //capture records within the target range
            if(this.totalRecords>=this.startIdx && this.totalRecords<this.endIdx){   
           
                this.tRecords.add( new CCWRow(c, false) );
            }
            
            //count the total number of records
            this.totalRecords++;
        
        }
        
        
        //calculate total pages
        Decimal pages = Decimal.valueOf(this.totalRecords);
        pages = pages.divide(Decimal.valueOf(PAGE_SIZE), 2);
        this.totalPages = (Integer)pages.round(System.RoundingMode.CEILING);
        
        //adjust start index e.g. 1, 11, 21, 31
        this.startIdx++;
        
        
        //adjust end index
        if(this.endIdx>this.totalRecords){
            this.endIdx = this.totalRecords;
        }
     
        
        //display resource usage
        System.Debug(LoggingLevel.WARN,'****** LIMIT query rows: '+Limits.getQueryRows()+' / '+Limits.getLimitQueryRows());
        System.Debug(LoggingLevel.WARN,'****** LIMIT heap size: '+Limits.getHeapSize()+' / '+Limits.getLimitHeapSize());
        System.Debug(LoggingLevel.WARN,'****** LIMIT cpu time: '+Limits.getCpuTime()+' / '+Limits.getLimitCpuTime());
       // System.Debug(LoggingLevel.WARN,'****** LIMIT script statements: '+Limits.getScriptStatements()+' / '+Limits.getLimitScriptStatements());
        
    }
        
    
    /*
    *   helper class that represents a row
    */
    public with sharing class CCWRow{
        
        public Contact tContact{get;set;}
        public Boolean IsSelected{get;set;}
        
        public CCWRow(Contact c, Boolean s){
            this.tContact=c;
            this.IsSelected=s;
        }
        
    } 

}



Enjoy the coding......





Saturday, December 27, 2014

What is @RemoteAction in Salesforce?

What is @RemoteAction in Salesforce and when we are going to use this @RemoteAction?

JavaScript remoting in Visualforce provides support for some methods in Apex controllers to be called via JavaScript.

JavaScript remoting has three parts:
  •  The remote method invocation you add to the Visualforce page, written in JavaScript.
  • The remote method definition in your Apex controller class. This method definition is written in Apex, but there are few differences from normal action methods.
  • The response handler callback function you add to or include in your Visualforce page, written in JavaScript.
To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form:
[namespace.]controller.method(    [parameters...,]    callbackFunction,    [configuration]);

  • namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if the class comes from an installed package.
  • controller is the name of your Apex controller.
  •  method is the name of the Apex method you’re calling.
  • parameters is the comma-separated list of parameters that your method takes.
  • callbackFunction is the name of the JavaScript function that will handle the response from the controller. You can also declare an anonymous function inline. callbackFunction receives the status of the method call and the result as parameters.
  • configuration configures the handling of the remote call and response. Use this to specify whether or not to escape the Apex method’s response. The default value is {escape: true}.


Example 1:

Visualforce Page:

<apex:page controller="AccountRemoteActionController">
    <script type="text/javascript">
    function getAccountJS() 
    {
        //get the values of input text and place into the variable.
        var accountNameJS = document.getElementById('accName').value;        
        AccountRemoteActionController.getAccount( accountNameJS, 
        function(result, event)
        {
        
          alert('event.status==>'+event.status);
          alert('event.type === '+event.type);
          alert('event.message ==>'+event.message);
            if (event.status) 
            {
                // demonstrates how to get ID for HTML and Visualforce tags
                document.getElementById("{!$Component.theBlock.thePageBlockSection.theFirstItem.accId}").innerHTML = result.Id;
                document.getElementById("{!$Component.theBlock.thePageBlockSection.theSecondItem.accNam}").innerHTML = result.Name;
            } 
            else if (event.type === 'exception') 
            {
                document.getElementById("errors-js").innerHTML = event.message;
            } else 
            {
                document.getElementById("errors-js").innerHTML = 'No Records Found..';
            }
        }, {escape:true});
    }
    </script>
    Account Name :<input id="accName" type="text" />
    <button onclick="getAccountJS()">Get Account</button>
    <div id="errors-js"> </div>
    <apex:pageBlock id="theBlock">
        <apex:pageBlockSection id="thePageBlockSection" columns="2">
            <apex:pageBlockSectionItem id="theFirstItem">
                <apex:outputText id="accId"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem id="theSecondItem" >
                <apex:outputText id="accNam" />
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

Controller Class:

global class AccountRemoteActionController
{
    public String accountName { get; set; }
    public static Account account { get; set; }
    //Default Constructor..
    public AccountRemoteActionController() {
    
    }
    
    @RemoteAction
    global static Account getAccount(String accountName) 
    {
        account = [select id, name, phone, type, numberofemployees from Account where name = :accountName ];
        return account;
    }
}


Out Put:

RemoteAction


Example 2:

In this example once the user selected a particular opportunity stage name then calling the remote method from java script and print the opportunity details in table format.

Visualforce Page :

<apex:page controller="OpportunityRemoteActionController" showHeader="true"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript"> function getStageJS(){ var oppStage= document.getElementById("{!$Component.theFm.oppStage}").value; alert("stageName==>"+oppStage); OpportunityRemoteActionController.getOpportunityDetails( oppStage, function(result, event){ // alert("event.status==>"+event.status); // alert("event.result==>"+event.result); var html = '<table border="thick solid">'; html = html + '<caption><b>Opportunity Details</b></caption><tr></tr>'; html = html + '<tr><th>Opportunity Name</th>'; html = html + '<th>Amount</th> </tr>'; if (event.status && event.result) { debugger; // alert("event.result[0].Name==>"+event.result[0].Name); for (var prop in event.result) { // important check that this is objects own property not from prototype prop inherited //alert(prop + " = " + event.result[prop].Name); html = html + '<tr><td><a href="'+event.result[prop].Name+'</td> <td>'+event.result[prop].Amount+'</td></tr> '; } html = html + '</table>'; // alert("html==>"+html); $("#opportunityDetails").html(html); } else { alert(event.message); } }, {escape:true}); } </script> <div align="center" width="550px"> <apex:form id="theFm"> <apex:selectList value="{!stageName}" size="1" id="oppStage" onchange="getStageJS()"> <apex:selectOptions value="{!options}"/> </apex:selectList> </apex:form> </div> <br/> <br/> <div id="opportunityDetails" align="center"> <!-- Opportunity details is displayed here. --> </div> </apex:page>

Controller Class:

global with sharing class OpportunityRemoteActionController { public Opportunity opp{get;set;} public String stageName{get;set;} public OpportunityRemoteActionController() { } /** * Method that creates the select option dynamically. **/ public List<SelectOption> getOptions() { List<SelectOption> options = new List<SelectOption>(); Schema.DescribeFieldResult fieldResult = Opportunity.StageName.getDescribe(); List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues(); options.add(new SelectOption('--Select--', '--Select--')); for( Schema.PicklistEntry f : ple) { //system.debug('f.getLabel()=>'+f.getLabel() +' ==f.getValue()' +f.getValue()); options.add(new SelectOption(f.getLabel(), f.getValue())); } return options; } /** * Remote action involved with Javascript remoting and is made global **/ @RemoteAction global static Opportunity[] getOpportunityDetails(String stageNameDet) { return [select id,Name,Amount,stageName from Opportunity WHERE stageName =: stageNameDet]; } }


Output:











 
| ,