[SalesForce] How to use External Ids in a Before Insert trigger

Our company deploys surveys from an external system. We receive them in Salesforce, but we don't have any relationships. I thought I could create the relationship with an External Ids in a Before Insert trigger, but it didn't work:

trigger SurveryTrigger on Survey__c (before insert) {
    if(Trigger.isBefore){
        if(Trigger.isInsert){
            for(Survey__c survey : Trigger.new){
                Account account = new Account();
                account.Foreign_key__c = survey.Account_key__c;
                survey.Account__r = account;
            }
        }
    }
}

Furthermore, I decided to refactor this into a class and it worked fine when I executed anonymously:

SurveyCreateRelationships createRelationships = new SurveyCreateRelationships();

Survey__c testSurvey = new Survey__c();
testSurvey.Account_key__c = 'xxxxxx';

List<Survey__c> testSurveys = new List<Survey__c>();
testSurveys.add(testSurvey);

createRelationships.CreateAccountRelationship(testSurveys);

insert testSurveys;

The only thing I can figure is that the before insert doesn't support creating this type of relationship. Has anyone had any similar trouble?

Best Answer

Old code contained a few errors. Here is the Trigger, and test code. This passed the apex test method in my org.

Apex Trigger
trigger surveyTrigger on Survey__c (before insert) { if(Trigger.isBefore){ if(Trigger.isInsert){ Map<String, String> extMap = new Map<String, String>(); Set<String> extIdSet = new Set<String>(); for(Survey__c survey : Trigger.new){ extIdSet.add(survey.Account_Key__c); } for(Account a : [select Id, Foreign_Key__c from Account where Foreign_Key__c IN :extIdSet]){ extMap.put(a.Foreign_Key__c, a.Id); } for(Survey__c survey : Trigger.new){ survey.Account__c = extMap.get(survey.Account_Key__c); } } } }

Test class @isTest private class TestSurveyTrigger { static testMethod void myUnitTest() { Account testAccount = new Account(Name='My test account', Foreign_Key__c='test123'); insert testAccount; Test.startTest(); Survey__c testSurvey = new Survey__c(Account_Key__c='test123'); insert testSurvey; Test.stopTest(); Survey__c result = [select Id, Account__c, Account__r.Name, Account__r.Foreign_Key__c from Survey__c where Account_Key__c = 'test123' limit 1]; system.assertEquals(testAccount.Id, result.Account__c); } }

Related Topic