Activity Forums Salesforce® Discussions How can I add a lookup relationship using an external id on a before insert/update trigger in Salesforce?

  • How can I add a lookup relationship using an external id on a before insert/update trigger in Salesforce?

    Posted by Prachi on December 3, 2019 at 4:58 am

    I would like to create a lookup relationship to a parent object using the parents external id from a before insert/update trigger. I am not receiving an error when I do this, but it is not creating the relationship. I have tested using anonymous apex with a dml and the code works fine. In the example, Tech1_ID__c is the external id of the Property__c object.

    trigger CaseAddressHandler on Case (before insert, before update) {
    for(Case c: trigger.new){
    c.Property__r = new Property__c(Tech1_ID__c =c.Property_Id__c);
    }
    }

    Yogesh replied 5 years ago 2 Members · 1 Reply
  • 1 Reply
  • Yogesh

    Member
    December 3, 2019 at 8:55 am

    Hello,

    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);
    }
    }

    Hope this helps!!

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos