+ Start a Discussion
Rajesh-InLoveWithSFdcRajesh-InLoveWithSFdc 

REST Connection Issue

Hi All,

Requirement : Connect two SFDC Dev Org using REST if Account Name in Teaget Exists through Error to User that Account Name already present in Target Org .

Steps a)  I have created Visualforce Pages and used Standard and Extension Controller as below 
                VF
                <apex:page standardcontroller="Account" extensions="MyController" tabStyle="Account">
    
 <apex:form >
      <!-- <apex:actionFunction action="{!InsertRecord}" name="InsertRecord_JS" oncomplete="CallWebService_JS();"/>
        <apex:actionFunction action="{!CallWebService}" name="CallWebService_JS" /> -->
      <apex:pageBlock >
        <apex:pageBlockSection columns="2" title="Account Information" collapsible="false" >
            <apex:inputField value="{!Account.Name}"/>
            <apex:inputField value="{!Account.Phone}"/>
            <apex:inputField value="{!Account.Site}"/>
            <apex:inputField value="{!Account.Type}"/>
            <apex:inputField value="{!Account.Industry}"/>
            <apex:inputField value="{!Account.AccountNumber}"/>
            <apex:inputField value="{!Account.AnnualRevenue}"/>
          <!--  <apex:inputcheckbox onclick="javaScrpt()" label="Check" value="{!test}"> -->
          <apex:actionRegion >
          <div align="center">
          <apex:outputLabel for="c1" value="Show Additional Information" style="font-weight:900"/>
          <apex:inputcheckbox label="Check" id="c1" value="{!checkinvalue}"> 
          <apex:actionSupport event="onclick" action="{!ActnMethod}" reRender="changeit" />
          </apex:inputcheckbox>
           </div>
            </apex:actionRegion>
      </apex:pageblockSection>
             
             <apex:outputPanel id="changeit">
             <apex:pageBlockSection columns="2" title="Additional Information" rendered="{!show}"  >
             <apex:inputField value="{!Account.CustomerPriority__c}"/>
             <apex:inputField value="{!Account.SLAExpirationDate__c}"/>
             <apex:inputField value="{!Account.SLA__c}"/>
             <apex:inputField value="{!Account.SLASerialNumber__c}"/>
             <apex:inputField value="{!Account.Active__c}"/>
             </apex:pageblockSection>
             </apex:outputPanel>
              
              <apex:pageblockButtons >
              <!--<div><input name="DoAction" class="btn" type="button" value="Do Action" onclick="InsertRecord_JS();return false;"/></div>-->
              <apex:commandButton action="{!Save1}" value="Save1"  />
              </apex:pageblockButtons>
              
       </apex:pageBlock> 
      
      
      
    </apex:form> 
    
  <!-- <script>
      function javaScrpt(){
       actionFunName(); 
      }
    </script>--->
     
</apex:page>

Custom COntroller 

Public class MyController {
Public Boolean show{get;set;}
Public Boolean checkinvalue{get;set;}
public Account acc {get;set;}
public MyController(ApexPages.StandardController controller) {
acc= (Account)controller.getRecord();
 }
public string ActnMethod(){
 if (checkinvalue==true)
    {
      show = true;
      }
      else
    {
      show = false;
      }
     return null;
    }
 Public pagereference Save1()
 {
     Integer r = SendAccountUsingRestApi.createAccount(acc.Name);
     System.debug('Value of r is'+r);
     if(r==200)
     {
         acc.Name.addError('Already Exist in the System');
     }
     else
     {
     upsert acc;
    return(new pagereference('/'+acc.id));
         
         
     }
     return null;
 }
}

b)  I have created the REST connection class to retrieve the result 
   public class SendAccountUsingRestApi {
String clientId='Ihavegivenmyclientsecret';
    String clientsecret='IhavegivenmyCLientID';
    string username='targetorguserdIdandPassword';
    String password='password+securitytokn';
    String accesstoken_url='https://login.salesforce.com/services/oauth2/token';
    String authurl='https://login.salesforce.com/services/oauth2/authorize';
    
  public class deserializeResponse{
      public String id;
      public String access_token;   
   }
    public String ReturnAccessToken(SendAccountUsingRestApi Acc){
        String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password; 
        Http h= new Http();
        HttpRequest req= new HttpRequest();
        req.setBody(reqbody);
        req.setMethod('POST');
       req.setEndpoint('https://ap4.salesforce.com/services/oauth2/token'); 
        HttpResponse res=h.send(req);
        System.debug(res.getBody()+'###1203res');
        deserializeResponse resp1=(deserializeResponse)JSON.deserialize(res.getBody(),deserializeResponse.class);
        System.debug(resp1+'###1203deserializeresponse');
        return resp1.access_token;
    }
 public static Integer  createAccount(String AccountName){
        SendAccountUsingRestApi acc1= new SendAccountUsingRestApi();
        String accessToken=acc1.ReturnAccessToken(acc1);
        Integer s;
        System.debug(accessToken+'###0012');
        if(accessToken!=null){
            String jsonstr='{"Name":"'+ AccountName +'"}';
            Http h2= new Http();
            HttpRequest req2= new HttpRequest();
            System.debug('Value of Auth Token is '+accessToken);
            req2.setHeader('Authorization','Bearer ' + accessToken);
            req2.setHeader('Content-Type','application/json');
            req2.setHeader('accept','application/json');
            req2.setBody(jsonstr);
            req2.setMethod('GET');
            req2.setEndpoint('https://ap4.salesforce.com/services/data/v39.0/sobjects/Account/');
            HttpResponse res2=h2.send(req2);
            s = res2.getStatusCode();}
          return s;
 }}

Issues: When i am creating Account which is not present in Target Org then also it is throwing Error in My Source Org ,But its creating the Account in Target Org as well, I am not able to understand why if someone can explain would be great help