+ Start a Discussion
Isak Stensmar 8Isak Stensmar 8 

Trigger - Need to update lookup field of existing record before/after insert

Hi,

I want to update an existing record Lookup field when I insert a new record.
My last post ( https://developer.salesforce.com/forums/?id=906F0000000DCnZIAW ) was also about linking records but in that case it was only the record that was inserted that was linked to an existing record.

What I want to accomplish this time is to update the lookup field on an existing record when a new record is inserted.
The problem I´ve faced so far is: 
-No ID before insert, so I can´t update lookup field in a (before insert) trigger (if I want to use the new record's ID that is).
-(After insert) trigger has ID, but you can´t update records in (after insert) triggers.

 Any suggestions/solutions?

Regards,
Isak
 
Praveen KHariPraveen KHari
Hi Isak,

If I understood your issue correctly.

You have two object for now let’s take ObjectA and ObjectB. 
ObjectB has a lookup field to ObjectA. 

Whenever you create a new record in ObjectA you want to link that record with ObjectB (may be based on some condition). So you will update ObjectB record after insert trigger of ObjectA. And you are not able to do that since it’s after trigger and before trigger you don't have the ID for ObjectA record. Is that correct?

Have tried future method?

-Praveen K Hari
Mahesh DMahesh D
Hi Isak,

Please find the code below:

Here

(1) I used future method to update the Lookup field.

Trigger:
Trigger MonthlyDonorAfterTrigger on MonthlyDonor__c (after insert) {
    MonthlyDonorHandler.populateIdValue(Trigger.newMap.keySet());
}
Class:
 
public class MonthlyDonorHandler {
    @future
    public static void populateIdValue(Set<Id> idSet) {
        List<MonthlyDonor__c> mdList = [Select Id, Name, Link_Objects__c from MonthlyDonor__c where ID IN: idSet AND Link_Objects__c = null];
        for(MonthlyDonor__c md: mdList) {
            md.Link_Objects__c = md.Id;
        }
        update mdList
    }
}

I added the null check in above query as I am assuming we have to update it only if it null, you can change accordingly based on your requirement.

Please do let me know if it helps you.

Regards,
Mahesh