• farukh sk hd
  • NEWBIE
  • 45 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 124
    Replies
Can somebody help me over here,I am getting error and I am not able to create a record using rest api from one salesforce org to other.

Here is my code,

public void getConList()
{

list<account> accList1=new list<account>();
String accToken;
string responseBody;
string endPoint='https://ap5.salesforce.com/services/apexrest/getAccountOnExternalId';
restApiClassSalesforceorg1 obj=new restApiClassSalesforceorg1();
accToken=obj.getRequestToken();
system.debug('access token'+ accToken);
if(accToken!='')
{
String accName1='Test from org 1 to org 2';
string Jsonstring='{"Name":"Acc from org 1"}';
Http h1=new Http();
HttpRequest req1=new HttpRequest();
req1.setHeader('Authorization','Bearer '+accToken);
req1.setHeader('Content-Type','application/json');
//req1.setHeader('accept','application/json');
req1.setMethod('POST');
req1.setBody(Jsonstring);
req1.setEndpoint(endPoint);
HttpResponse hresp1=h1.send(req1);
system.debug('hresp1'+ hresp1);
//listWrap=(list<resultWrapper>) JSON.deserialize(hresp1.getBody(),list<resultWrapper>.class);

}

// return listWrap;

}





@RestResource(urlMapping='/getAccountOnExternalId/*')
   global with sharing class getAccount {
     @HttpPost
      global Static string fetchAccount(string name1){
      Account obj=new account();
      obj.name=name1;
      Insert obj;
        
        return 'Success';
      }
   }
Can somebody help me here I am getting the error while getting data based on id which I am passing, I am able to generate session id as well.

Salesforce to Salesforce Rest Api Integration.

My code is,

public class restApiClassSalesforceorg1{


private string cKey='XXXXXX';
private string cSecret='XXXXXX';
private string uName='XXXXXX';
private string passwd='XXXXXX';

// Above information is hided


public class responseWrapper{

public string id;
public string access_token;
public string instance_url;

}

public string getRequestToken()
{
string reqBody='grant_type=password&client_id='+cKey+'&client_secret='+cSecret+'&username='+uName+'&password='+passwd;                                      

Http h=new Http();
HttpRequest req=new HttpRequest();
req.setBody(reqBody);
req.setMethod('POST');
req.setEndpoint('https://login.salesforce.com/services/oauth2/token');

HttpResponse hresp=h.send(req);
responseWrapper wResp=(responseWrapper)JSON.deserialize(hresp.getBody(),responseWrapper.class);
system.debug('Instance url'+wResp.instance_url);
system.debug('session id'+wResp.access_token);
return wResp.access_token;


}

public static list<Account> getConList()
{
list<account> accList1=new list<account>();
String accToken;
string ExternalId='SomeIDfromOtherOrg';
string responseBody;
string endPoint='https://ap5.salesforce.com/services/apexrest/v1/getAccountOnExternalId/' + ExternalId;
restApiClassSalesforceorg1 obj=new restApiClassSalesforceorg1();
accToken=obj.getRequestToken();
system.debug('access token'+ accToken);
if(accToken!='')
{
Http h1=new Http();
HttpRequest req1=new HttpRequest();
req1.setHeader('Authorization','Bearer'+accToken);
req1.setHeader('Content-Type','application/json');
//req1.setHeader('Accept','application/json');
req1.setMethod('GET');
req1.setEndpoint(endPoint);
HttpResponse hresp1=h1.send(req1);
responseBody=hresp1.getBody();
JSONParser parser=JSON.createParser(responseBody);
 while (parser.nextToken() != null) {
 Account obj1=new Account();
 if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'Name')) {
 
 string accName=parser.getText();
 obj1.name=accName;
 
 }
accList1.add(obj1);
}
}
return accList1;

}



}

Code from other org,

@RestResource(urlMapping='/v1/getAccountOnExternalId/*')
   global with sharing class getAccount {
     @Httpget
      global static list<Account> fetchAccount(){
        RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        string accId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        list<Account> lstAcc=[Select id , name,ExternalIdForAccount__c from Account where Id=:accId ];
        
        return lstAcc;
      }
   }


 
Can somebody help me over here,I am getting error and I am not able to create a record using rest api from one salesforce org to other.

Here is my code,

public void getConList()
{

list<account> accList1=new list<account>();
String accToken;
string responseBody;
string endPoint='https://ap5.salesforce.com/services/apexrest/getAccountOnExternalId';
restApiClassSalesforceorg1 obj=new restApiClassSalesforceorg1();
accToken=obj.getRequestToken();
system.debug('access token'+ accToken);
if(accToken!='')
{
String accName1='Test from org 1 to org 2';
string Jsonstring='{"Name":"Acc from org 1"}';
Http h1=new Http();
HttpRequest req1=new HttpRequest();
req1.setHeader('Authorization','Bearer '+accToken);
req1.setHeader('Content-Type','application/json');
//req1.setHeader('accept','application/json');
req1.setMethod('POST');
req1.setBody(Jsonstring);
req1.setEndpoint(endPoint);
HttpResponse hresp1=h1.send(req1);
system.debug('hresp1'+ hresp1);
//listWrap=(list<resultWrapper>) JSON.deserialize(hresp1.getBody(),list<resultWrapper>.class);

}

// return listWrap;

}





@RestResource(urlMapping='/getAccountOnExternalId/*')
   global with sharing class getAccount {
     @HttpPost
      global Static string fetchAccount(string name1){
      Account obj=new account();
      obj.name=name1;
      Insert obj;
        
        return 'Success';
      }
   }
0down votefavorite
I need to make integration between Org1 and Org2. We created a callout POST. When we create an object in Org1, we also create an object in Org2. POST work. All is Ok. Now I need also delete an object in Org2, if External Id in this obj == Id in obj from Org1.
Something like that:
If(org2Object.ExternalId == org1Object.Id){
   Delete org2Object;
}

I try to delete a record from another org, but I don't know, how to write it right. My Delete callout:
private static Position__c pos = [SELECT Id, Name, Location__c, Job_Description__c, Salary_Range__c, Skills_Required__c, Education__c,
                       Hiring_Manager__r.Name, Email__c, Phone__c, Status__c
                       FROM Position__c WHERE Name = 'Title22'];

public static String getRequestBody(){
    Settings__c settings = [SELECT ConsumerKey__c, ClientSecret__c, Username__c, Password__c, SecurityToken__c
                            FROM Settings__c
                            WHERE Name = 'OurSettings'];  
    String consumerKey = settings.ConsumerKey__c;
    String consumerSecret = settings.ClientSecret__c;
    String username = settings.Username__c;
    String password = settings.Password__c + settings.SecurityToken__c;
    String request = 'grant_type=password&client_id=' + consumerKey +'&client_secret=' + consumerSecret +
                     '&username=' + username + '&password='+password;
    return request;
}


public static void deleteCalloutResponseContents(Id ourId){
    Http ourHttp = new Http();
    HttpRequest request = httpRequest('DELETE');
    HttpResponse response = ourHttp.send(request);
    OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(response.getbody(), OAuth2.class);

    if(objAuthenticationInfo.ACCESS_TOKEN != null){
        pos.Id = ourId;

        HttpRequest finalRequest = new HttpRequest();
        String jsonstr='{"Position_ID__c":"'+ ourId +'"}';

        finalRequest.setHeader('Authorization','Bearer '+ objAuthenticationInfo.ACCESS_TOKEN);
        finalRequest.setHeader('Content-Type','application/json');
        finalRequest.setHeader('accept','application/json');
        finalRequest.setBody(jsonstr);
        finalRequest.setMethod('DELETE');

        request.setEndpoint(System.Label.Job_Advertisement_URL + '/services/data/v43.0/sobjects/Job_Advertisement__c/ourId');
        response = ourHttp.send(finalRequest);
        System.debug('RESPONSE BODY: ' + response.getBody());
    }        
}

public class OAuth2{
        public String ACCESS_TOKEN{get;set;}    
    }

How can I fix it?
Requirement: There is a button "Export Today "  which is used to export account records in the form of csv in lightning component(Account_Detail_Component).In the helper ,we have "convertArrayOfObjectsToCSV" function which is used to convert object records into csv. I am able to display account fields values i.e 'Name','AccountNumber','Id'  in csv.But I am not able to display parent account field values.
For example below query return account field values and parent field value 
Select id,name,accountnumber,parent.accountnumber from Account where parent.id!=null and parent.accountnumber!=null.Could any one please post javascript code which needs to be used in helper fucntion for displaying parent  account records.


User-added image


Component:
<aura:component  controller="CsvDownloadCtrller" implements="force:appHostable">
    <aura:attribute name="AcctLst" type="Account[]"></aura:attribute>
    <aura:handler name="init" value="{!this}" action="{!c.loadAcctRcrds}"/>
    <div class="slds-box slds-box">
  <article class="slds-card">
  <div class="slds-card__header slds-grid">
    <header class="slds-media slds-media_center slds-has-flexi-truncate">
      
      <div class="slds-media__body">
        <h2 class="slds-card__header-title">
          <a href="javascript:void(0);" class="slds-card__header-link slds-truncate" title="Accounts">
            <span class="slds-text-heading_small">Account List View</span>
          </a>
        </h2>
      </div>
        
      <div class="slds-no-flex">
        <button class="slds-button slds-button_brand" onclick="{!c.exprtTodysRecrds}">Export Today</button>
        <button class="slds-button slds-button_brand">Export Weekly</button>  
      </div>
    </header>
  </div>
</article>
        
 <article class="slds-card">
  <div class="slds-card__header slds-grid">
    <header class="slds-media slds-media_center slds-has-flexi-truncate">
      
      <div class="slds-media__body">
        <h2 class="slds-card__header-title">
          <a href="javascript:void(0);" class="slds-card__header-link slds-truncate" title="Accounts">
            <span class="slds-text-heading_small">Search Accounts</span>
          </a>
        </h2>
      </div>
      
    </header>
  </div>
</article>
<div class="slds-form slds-form_compound">
    <fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
<lightning:select name="select1" label="Account Type" required="true">
        <option value="">choose one...</option>
        <option value="1">one</option>
        <option value="2">two</option>
        <option value="3">three</option>
        <option value="4">four</option>
        <option value="5">five</option>
    </lightning:select>
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:input aura:id="field" label="Parent Account Number" name="ParentAccountNumber"  />
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:input aura:id="field" label="Account Number" name="AccountNumber"  />   
</div>    
</div>
</div>
</fieldset>
 <fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">    
<div class="slds-form-element slds-size_1-of-2">
    <lightning:textarea name="input1" label="Description" />    
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:select name="select1" label="Country" required="true">
        <option value="">choose one...</option>
        <option value="1">one</option>
        <option value="2">two</option>
        <option value="3">three</option>
         <option value="4">four</option>
    </lightning:select>  
</div>    
</div>
</div>
</fieldset> 
 <fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">    
<div class="slds-form-element slds-size_1-of-2">        
</div>
<div class="slds-form-element slds-size_1-of-2">    
</div>    
</div>
</div>
</fieldset>
 <fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">    
<div class="slds-form-element slds-size_1-of-2">        
</div>
<div class="slds-form-element slds-size_1-of-2">    
</div>    
</div>
</div>
</fieldset>          
 <fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">    
<div class="slds-form-element slds-size_1-of-2">
        
</div>
<div class="slds-form-element slds-size_1-of-2"> 
    <lightning:input type="date" name="input1" label="From Date" /> 
</div>    
</div>
</div>
</fieldset>   
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">    
<div class="slds-form-element slds-size_1-of-2">        
</div>
<div class="slds-form-element slds-size_1-of-2"> 
    <lightning:input type="date" name="input1" label="To Date" /> 
</div>    
</div>
</div>
</fieldset>  
</div>
       
<div class="slds-no-flex slds-align_absolute-center slds-m-top_xx-large">
        <button class="slds-button slds-button_brand" style="width:100px">Search</button>
        <button class="slds-button slds-button_brand" style="width:100px">Clear</button>  
      </div> 
</div> 
</aura:component>

controller:
({
    loadAcctRcrds:function(component,event,helper){
        
       var action = component.get("c.getAccounts");
        action.setCallback(this,function(response){
        var state = response.getState();
            
            
            
            if(state == "SUCCESS"){
                
                component.set("v.AcctLst",response.getReturnValue());
                
            }
            else{
                alert('failed');
                
            }
        });
        $A.enqueueAction(action);      
        
    },
    
    exprtTodysRecrds : function(component, event, helper) {
         var stockData = component.get("v.AcctLst")    
         var csv = helper.convertArrayOfObjectsToCSV(component,stockData);
          if (csv == null){return;} 
        
        // ####--code for create a temp. <a> html tag [link tag] for download the CSV file--####     
         var hiddenElement = document.createElement('a');
          hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
          hiddenElement.target = '_self'; // 
          hiddenElement.download = 'ExportData.csv';  // CSV file Name* you can change it.[only name not .csv] 
          document.body.appendChild(hiddenElement); // Required for FireFox browser
          hiddenElement.click(); // using click() js function to download csv file
        
        
    }
})


Helper:

({
        
    convertArrayOfObjectsToCSV : function(component,objectRecords){
        // declare variables
        var csvStringResult, counter, keys, columnDivider, lineDivider,parentKey;
       
        // check if "objectRecords" parameter is null, then return from function
        if (objectRecords == null || !objectRecords.length) {
            return null;
         }
        // store ,[comma] in columnDivider variabel for sparate CSV values and 
        // for start next line use '\n' [new line] in lineDivider varaible  
        columnDivider = ',';
        lineDivider =  '\n';
 
        // in the keys valirable store fields API Names as a key 
        // this labels use in CSV file header  
        keys = ['Name','AccountNumber','Id','Parent' ];
        //parentKey=['AccountNumber'];
        
        csvStringResult = '';
        csvStringResult += keys.join(columnDivider);
        csvStringResult += lineDivider;
 
        for(var i=0; i < objectRecords.length; i++){   
            counter = 0;
           
             for(var sTempkey in keys) {
                var skey = keys[sTempkey] ; 
                 
                /* if(skey=='Parent'){
                     for(var pTempkey in parentKey){
                         csvStringResult += '"'+ objectRecords[i][skey][pTempkey]+'"';                       
                         
                     }    
                     
                     
                 }*/
                
 
              // add , [comma] after every String value,. [except first]
                  if(counter > 0){ 
                      csvStringResult += columnDivider; 
                   }   
               
               csvStringResult += '"'+ objectRecords[i][skey]+'"'; 
               
                /* if(csvStringResult.includes("Parent")){
                     for(var sTemp in parentKey){
                         var orgnKey = parentKey[sTemp];        
                        csvStringResult += '"'+ objectRecords[i][skey][orgnKey]+'"'; 
                         
                     }
                     
                 } */ 
                 
                 
               
               counter++;
             
             } // inner for loop close     
             csvStringResult += lineDivider;
          }// outer main for loop close 
       
       // return the CSV formate String 
        return csvStringResult;        
    },

})

Apex Controller:

public class CsvDownloadCtrller {
    
    @AuraEnabled
    public static List<Account> getAccounts(){
       return [Select id,name,accountnumber,parent.accountnumber from Account where parent.id!=null and parent.accountnumber!=null];
              
        
    } 

}







 
hi guys,

i will try to create and update a record in SFDC via API. I have acheived to create a Record .But I can't able to update  the Record via API . 

Here is my sample code :
        public void UpdatedRecordforAccount()
        {
            //0017F00000b9EnPQAU
            HttpClient client = new HttpClient();
            string requestMessage = "{\"Name\":\"Express Logistics and Transport Sample\"}";


            HttpContent content = new StringContent(requestMessage, Encoding.UTF8, "application/json");            
            string uri = InstanceUrl + API_ENDPOINT + "sobjects/Account/0017F00000b9EnPQAU" + "?_HttpMethod=PATCH";

            //create request message associated with POST verb
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);

            //add token to header
            request.Headers.Add("Authorization", "Bearer " + AuthToken);

            //return xml to the caller
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.Content = content;
            var response = client.SendAsync(request).Result;
            Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            Console.ReadLine();
        }

I have already tried these two method (http put,post) and _Patch concept. If any have a solution .please share to me 
Hi Salesforce Developers,
I have an inline Visualforce page on account detail page. And there is lightning component inside this VF page. There is some table of data and a "Download" button to download the given table as csv/excel. On button click, I tried to create CSV file using below code. 
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_self'; //
hiddenElement.download = 'ExportData.csv';  // CSV file Name* you can change it.[only name not .csv]
document.body.appendChild(hiddenElement); // Required for FireFox browser
hiddenElement.click(); // using click() js function to download csv file
This is working in classic but not in Lightning. Below error is shown in lightning.
Error shown in Lightning
Any help would be much appreciated.
I have a lightning component that implements lightning:actionOverride how do I get the recordId of the parent when the action is triggered from a related list?
I am new for Integration , Please help me  How to establish a connection One Org to another Org by using Rest API Oauth 2 and Consumer Id and consumer Secret .

Could you please give me sample code ......       

Thanks in advance
  • January 04, 2017
  • Like
  • 0
Hi All, 

Our Requirement:

We have built a custom report in Lightning using lightning component as per the customer requirement.
Customer would like to have a downloadable as CSV for this custom report so that users can just download it and it will be downloaded with all the records with out any limits.

Currently we are sending out an email of custom report which is having heap size limit.
Quick help would be much appreciated.

Thanks
Hi friends
This is an urgent requirement, kindly help.
I have two different salesforce accounts  and I am trying to delete records based on criteria using rest api annotation @HttpDelete

The code in destination is:
@HTTPDelete 
 webservice static string DeleteAccounts()  
 {
    Account a=[select Id from account where Name LIKE :'%TVS Electronics%'];
    return a.ID;
 }
}
The code in source is:

          Http h = new Http();
         
          HttpRequest req = new HttpRequest();
       
          req.setMethod('DELETE');
       
          req.setHeader('Authorization','Bearer '+Helper.GetAccessToken().access_token);
       
          req.setHeader('Content-Type','application/json; charset=UTF-8');
         
          //call the rest resource URL and this url needs to be registered in remote settings
          req.setEndpoint('https://ap2.salesforce.com/services/apexrest/AccountRest');  
           
          HttpResponse res = h.send(req); // JSON string is generated at this point
 system.debug('---res.getBody()--'+res.getBody());

In res.getBody() , I am getting the ID of the record which was passed from source
Now how do I pass this ID back to source indicating that this record is to be deleted.

I hope I am clear

Thanks
pooja
 
Hi,
Can we export list of records from a lightning page to Excel sheet on click of button?In VF pages we use ContentType ,how can we do the same in Lightning?

Thanks in advance
friends
can we call Database.executebatch in trigger?
if yes, then how to do and if no what can be the limitation.
concrete example will be helpful

sonali​​​​
Dear Salesforce Specialists,

You guys are doing awesome Job in providing the best knowledge for almost all the questions posted on forums,

I do have a request :

I am very new to the Webservices & Integration

1) How to learn Web services - Integration & Where to start ( Step - By Step Resources : Documentation , PDF's , VIdeo;s , Usefull Blogs ? )

2) Salesforce Rest & Soap - Where to start ( Step - By Step Resources : Documentation , PDF's , VIdeo;s , Usefull Blogs ? )

3) Any Real-time impmemention's ( With : Oracle, SAP, SQL,JAVA) for references ?

4) Does big Clients use Third-Party tools for automating Integration ( Ex: Jitterbit , Boomi , Informatica ) , If so which one is best tool to use ?

One of our client project is about to start and I am involved in that and I am in real confusion from where to start learning and reach the stage of implementing?

I hope some of you guys helps me ,

Thanks,
Janardhan
 
Hello Experts,
I have registered my app. Could you please help in letting me know how to get:
1. client_id,
2. client secret, and
3. security token

I am trying to implement Oauth pragramatically so that I can use REST API.

Could you please help.

Thanks,
Rakesh

Hi,

 

We are looking to  create a record (Asset) as an appliance in an external system from Salesforce.

 

This would get triggered when a button is clicked upon on the Asset object

 

Can you please guide to some code samples that use REST APIs to connect to external systems and insert records in it and in return fetch a value which is created in the external system.

 

 

Requests:


Action |HTTP Method| URL|
Create | POST | http://xyz.com/sfapi/appliance/
Read GET http://rxyz.com/sfapi/appliance/:id
Update PUT http://xyz.com/sfapi/appliance/:id
Delete DELETE http://rmc.com/sfapi/appliance/:id

 

 

i want to create a method (via PUT) of the Apex REST web service  to receive a list of string and also the code to invoke it from java.

  • December 06, 2011
  • Like
  • 0

Hello,

 

I want to Export Data to CSV file from Custom object in Salesforce throug Apex Code.

It would be great that anybody provide some sample code.

 

Thanks For Your Co-operation

  • April 30, 2011
  • Like
  • 0

 how to call the batch Apex class using trigger.

  • December 17, 2010
  • Like
  • 0