[SalesForce] Updating lookup field on a custom object using another text field as a reference

Very new to coding and need a little help populating a lookup field.

I have object Account and custom object Order__c. On Account we have a Ship_to_Code__c which stores an ID. This ID is also part of the custom Order__c object, Ship_to_Code_del__c

Orders__c has a lookup to Account. When creating (or importing from dataloader) an Order__c record, I would like to auto populate the account lookup field with the Account name where there is a match on the ship to code IDs.
My code below is running without errors, but not returning any account names in the lookup field. I suspect its something to do with line 16 and not correctly asking for the account id value:

trigger TestOrders on Order__c(before insert, before update, after insert) {
    set < string > setIds = new set < string > ();
    Map < String, Id > mapMatch = new Map < String, Id > ();
    for (Order__c Order: Trigger.New) {
        setIds.add(Order.Ship_To_Code_del__c);
    }
    for (Account acc: [Select Id, Ship_To_Code__c from Account where Ship_To_Code__c IN: setIds]) {
        mapMatch.put(acc.Ship_To_Code__c, acc.Id);
    }
    for (Order__c Order: Trigger.New) {
        if (mapMatch.containsKey(Order.Ship_To_Code_del__c)) {
            Order.SFDC_Account_Name__c = mapMatch.get(Order.Ship_To_Code_del__c);
        }
    }
}

Best Answer

I cannot comment right Now, but I want to understand why you have used after insert event in this trigger. According to me this should only be on before insert and before update event as you are updating same object's field.

Update : I just checked, while you use after insert in the trigger it will give you exception(

System.FinalException: Record is read-only

) because you are trying to update new list in after insert event.

Related Topic