Getting record from other Salesforce organization OR communication between multiple salesforce organization

Get articles everyday as a email directly to your inbox:
Click to publicize, if you like this article :

In this article, i will explain the code which can be used for connecting and getting the records from different or multiple salesforce organization using Apex and REST Service.

To start first we will need to authorize below two URL which can be accessed from salesforce environment.
This can be done from “Setup | Administration Setup | Security Controls | Remote Site Settings”

  1. https://www.salesforce.com
  2. https://ap1-api.salesforce.com
Salesforce Remote Site Setting

Salesforce Remote Site Setting


It is possible that you may need to change first URL it may be https://www.na1-api.salesforce.com or https://www.na2-api.salesforce.com

This application will prompt for the Username and Password of the other salesforce account and display the 10 records of the Account.

Connect Other Salesforce Account - Output Screen

Connect Other Salesforce Account - Output Screen

Apex Code:

public with sharing class FetchAccount {

    //Login Domain May be test, prerellogin.pre
    String LOGIN_DOMAIN = 'www';
    public String pwd{get;set;}
    public String userName{get;set;}
    public List<Account> acc{get;set;}
    public String errMsg{get;set;}
    public String displayError{get;set;}

    public FetchAccount()
    {
        displayError = 'none';
    }

    public void fetch()
    {
        errMsg  = 'Some error occurred, please try again';
        try
        {
        //-----------------------------------
        // Login via SOAP/XML web service api
        //-----------------------------------
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://' + LOGIN_DOMAIN + '.salesforce.com/services/Soap/u/22.0');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
        request.setHeader('SOAPAction', '""');
        //not escaping username and password because we're setting those variables above
        //in other words, this line "trusts" the lines above
        //if username and password were sourced elsewhere, they'd need to be escaped below
        request.setBody('<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' + userName+ '</username><password>' + pwd+ '</password></login></Body></Envelope>');
        Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
          .getChildElement('Body', 'http://schemas.xmlsoap.org/soap/envelope/')
          .getChildElement('loginResponse', 'urn:partner.soap.sforce.com')
          .getChildElement('result', 'urn:partner.soap.sforce.com');

        //-------------------------------
        // Grab session id and server url
        //--------------------------------
        final String SERVER_URL = resultElmt.getChildElement('serverUrl', 'urn:partner.soap.sforce.com') .getText().split('/services')[0];
        final String SESSION_ID = resultElmt.getChildElement('sessionId', 'urn:partner.soap.sforce.com') .getText();

        //----------------------------------
        // Load first 10 accounts via REST API
        //---------------------------------
        final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
        theUrl.getParameters().put('q','Select a.Phone, a.Name, a.CreatedBy.FirstName, a.CreatedById From Account a limit 10');
        request = new HttpRequest();
        request.setEndpoint(theUrl.getUrl());
        request.setMethod('GET');
        request.setHeader('Authorization', 'OAuth ' + SESSION_ID);

        String body = (new Http()).send(request).getBody();

        JSONParser parser = JSON.createParser(body);

        do{
            parser.nextToken();
        }while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));

        parser.nextToken();

        acc = (List<Account>) parser.readValueAs(List<Account>.class);
        }
        catch(Exception e)
        {
            displayError = 'block';
        }

    }
}

Visualforce Code:

<apex:page controller="FetchAccount" standardStylesheets="true">
<style type="text/css">
.errorMsg{
    font-size:0.8 em;
    color:red;
}
</style>
<apex:pageBlock >
<apex:form >
<apex:outputLabel value="UserName : " for="userName"/>
<apex:inputText required="true" id="userName" value="{!userName}" />
<br />
<apex:outputLabel value="Password : " for="pwd"/>
<apex:inputsecret id="pwd" value="{!pwd}"/>
<br />
<apex:commandButton id="getRecords" value="Get Records" action="{!fetch}" rerender="wrapper" status="waitStatus" />
<apex:actionStatus startText="Requesting..." stopText="" id="waitStatus"/>
<hr />
<apex:outputPanel id="wrapper">
<div class="errorMsg" style="display:{!displayError}"> {!errMsg} </div>
<apex:pageBlockTable value="{!acc}" var="account" id="accTable" rowClasses="odd,even" styleClass="tableClass">

    <apex:column >
        <apex:facet name="header">Account Name</apex:facet>
         <apex:outputText value="{!account.name}"/>
    </apex:column>

    <apex:column >
        <apex:facet name="header">Created By</apex:facet>
         <apex:outputText value="{!account.CreatedBy.FirstName}"/>
    </apex:column>

    <apex:column >
        <apex:facet name="header">Phone</apex:facet>
         <apex:outputText value="{!account.Phone}"/>
    </apex:column>

</apex:pageBlockTable>
</apex:outputPanel>
</apex:form>
</apex:pageBlock>
</apex:page>

Possibly Related posts:

  1. Passing multiple Parameters in ActionFunction in Visualforce
  2. Dynamic Approval Process in Salesforce based on the Apex and Trigger
  3. Latest Salesforce Interview Questions – Part 4 – Related to Dynamic Apex
  4. Email Services in Salesforce with simple example
  5. Salesforce Tutorial – Create Simple Ajax based Visualforce page
You can leave a response, or trackback from your own site.
  • Sukumar

    iam trying to (selected check list lead ids ,text field  have  ( i written something  the text field)     message will be sent  the particular lead emails) how to solve plz tell me……… but the error occured

    public class leadmails {

       
    public leadmails()
    {
    }

    private final List leadids;
      public List ld;
      public leadmails(ApexPages.StandardController controller)
      {
         ld = [select Id from lead limit 10 ];
         for(Integer i=0;i<10;i++)
         {
             leadids.add(ld[i].Id);
          } 
      }

       
    public class leadwrap
    {

    public ID id;
    public string lname{get;set;}
    public string company{get;set;}
    public string email{get;set;}
    public boolean check{get;set;}
    public string emailtext{get;set;}
    }
     list lw = new list();
     public list getinfo()
     {
     list ls=[select id,name, Company,email,emailtext__c from lead];
     for(lead l:ls)
     {
     leadwrap w = new leadwrap();
     w.id=l.id;
     w.lname=l.name;
     w.company=l.company;
     w.email=l.email;
     w.emailtext=l.emailtext__c;
     lw.add(w);
     }
     return lw;
     }
     list dlist=new list();
     lead le;
     public pagereference send()
     {
     for(leadwrap lp:lw)
     {
     if(lp.check == true)
     {
     le=[select id from lead where id=:lp.id];
     dlist.add(le);
     }
     }
     update dlist;
     
     pagereference pr= page.leadmail;
     pr.setredirect(true);
     return pr;
     
     
      
     
     Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
           mail.setTargetObjectIds(leadids);
           mail.setTemplateId(”);
          Messaging.SendEmailResult [] r =  Messaging.sendEmail(new Messaging.massEmailMessage[] {mail});
    return null;

           }
           }

    • JitendraZaa

      Hi,
      What actually you are trying to achieve and what error you are getting?

      • Sukumarmalladi22

         hi
        error is     Illegal assignment from LIST to LIST
        Error occurred
        loading controller ‘leadmails’ for page leadmail

        and my requirment is like  selected check list lead ids ,text field  have  ( i written something 
        the text field)     message will be sent  the particular lead emails)
        how to solve plz tell me……… but the error occured

  • Anonymous

    sir i want to hello world program plz send mail

    • Anonymous

      Hello world program of what?
      if you are talking about the salesforce tutorial from starting then this article might be very useful to you.
      http://shivasoft.in/blog/salesforce/step-by-step-salesforce-tutorial-creating-custom-object-1-of-n/

      Regards,
      Jitendra Zaa

      • Sukumar

        iam trying to (selected check list lead ids ,text field  have  ( i
        written something  the text field)     message will be sent  the
        particular lead emails) how to solve plz tell me……… but the error
        occured

        public class leadmails {

           
        public leadmails()
        {
        }

        private final List leadids;
          public List ld;
          public leadmails(ApexPages.StandardController controller)
          {
             ld = [select Id from lead limit 10 ];
             for(Integer i=0;i<10;i++)
             {
                 leadids.add(ld[i].Id);
              } 
          }

           
        public class leadwrap
        {

        public ID id;
        public string lname{get;set;}
        public string company{get;set;}
        public string email{get;set;}
        public boolean check{get;set;}
        public string emailtext{get;set;}
        }
         list lw = new list();
         public list getinfo()
         {
         list ls=[select id,name, Company,email,emailtext__c from lead];
         for(lead l:ls)
         {
         leadwrap w = new leadwrap();
         w.id=l.id;
         w.lname=l.name;
         w.company=l.company;
         w.email=l.email;
         w.emailtext=l.emailtext__c;
         lw.add(w);
         }
         return lw;
         }
         list dlist=new list();
         lead le;
         public pagereference send()
         {
         for(leadwrap lp:lw)
         {
         if(lp.check == true)
         {
         le=[select id from lead where id=:lp.id];
         dlist.add(le);
         }
         }
         update dlist;
         
         pagereference pr= page.leadmail;
         pr.setredirect(true);
         return pr;
         
         
          
         
         Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
               mail.setTargetObjectIds(leadids);
               mail.setTemplateId(”);
              Messaging.SendEmailResult [] r =  Messaging.sendEmail(new Messaging.massEmailMessage[] {mail});
        return null;

               }

  • Anonymous

    Hi,
    Please add “https://www.salesforce.com” in remote site. Let me know if you face error.

    Regards,
    Jitendra Zaa