0

I know that with External Id, I can upsert a record and that will Insert or Update the record base on the External Id (update if exists or insert if not) instead of the regular Id.

Is there is a way to update\ insert a record based on its external Id?

Example (Code__c is an external Id):

List<Example__c> ExampleList= [SELECT Id,Code__c,Name FROM Example__c LIMIT 1]; 
SomeObjectInstance.someLookupField__c = ExampleList[0].Code__c;
insert(SomeObjectInstance);


instead of:
SomeObjectInstance.someLookupField__c = ExampleList[0].Id;
insert(SomeObjectInstance);

What about upsert a related object based on the external Id?

For Example :

Contact con = new Contact();
con.City_Code = getCity('PKR'); // Getcity is the function below

//what should I do now with the contact? 

public static String getCity(String wsDemoCity){
    List<City__c> countryList = [
        SELECT Id,Code__c,City_Name_Eng__c FROM 
        City__c WHERE Code__c =:wsDemoCity LIMIT 1
    ];
    if(countryList.size()>0){  
        return countryList[0].code__c;
    }
}
  • Yes, it is possible to insert or update using a external id. What how are you planning to insert or update those records? DataLoader, Integration , ... ? You can create a process to do this. – Carlos Naranjo Nov 27 '18 at 13:50
  • Thank you ! I updated the question' below the '---' can you please look at it again? And for your question - its via apex - webservice rest API @Carlos Naranjo – Salvation Nov 27 '18 at 14:29
  • An external id is not always unique – Pranay Jaiswal Nov 27 '18 at 14:32
1

Instead of insert/update just call upset and specify the external id. The operator will handle it for you.

SomeObjectInstance.someLookupField__c = ExampleList[0].Code__c;
upsert SomeObjectInstance someLookupField__c; 

*Given that someLookupField__c is also an external id field.

Src: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_examples_upsert.htm?search_text=upsert

| improve this answer | |
  • Hi @Pranay Jaiswal, I updated the wauestion below the '--' can you please look at it again? – Salvation Nov 27 '18 at 14:28
  • Is city code external id for contact? – Pranay Jaiswal Nov 27 '18 at 14:29
  • No, the city_code is the external Id for the City object but City have a lookup relationship with Contact. (The Contact object have the lookup for city) – Salvation Nov 27 '18 at 14:32
  • No you cannot use upsert then...., upsert can only work for object that have an externalID field, as you contact doesn not have that, it wont work. You can use simple upsert. ie Upsert based on Id field. – Pranay Jaiswal Nov 27 '18 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.