Populating lookup fields using an external ID

I have an lookup field in my opportunity object which is pointing to a custom object called Code__c.

Code__c has an external Id field called Code_Source__c.

When creating an opportunity once way of linking the opportunity to Code__c is by passing Id.

Opportunity op = new Opportunity(Name = 'Test Op', StageName = 'Open', ... , Oppoortunity_Code__c =code.Id );

Is it possible to use external ID (Code_Source__c) instead of the code.Id?


//create an in-memory instance of code, with the external id set
Code__c code = new Code__c(Code_Source__c = 'EXTERNAL_ID_HERE');

//create an instance of Opportunity, and point to the instance of code created above
Opportunity op = new Opportunity(Name = 'Test Op', StageName = 'Open', ... , Oppoortunity_Code__r = code );

upsert op;

Source : Link , Question Author : Yash Mehta , Answer Author : techtrekker

Leave a Comment