function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
pavan mithunpavan mithun 

How to update a lookup field on a object based on matching of custom id filed value of parent and lookup object.

Hi all, I have custom object "Role" for that i have "Id" field  and a Account lookup also. In Account object i have a Custom Id field and if the Id field values of both Role and Account object are same the Account lookup field on Role object should be update automatically with that Account Name. How do I write a trigger for it?

Thanks in Advance..
Waqar Hussain SFWaqar Hussain SF
Trigger Role__c RoleTrigger(before insert, before update) {
    set < Id > CustomIds = new set < Id > ();
    for (Role__c role: trigger.new) {
        if (role.Custom_ID__c != null)
            CustomIds.add(role.Custom_ID__c);
    }

    List < Account > Accs = new list < Account > ();
    Accs = [Select Id, Account_Custom_ID__c from Account where  Account_Custom_ID__c IN: CustomIds];
    Map < string, Account > AccountMap = new Map < String, Account > ();
    for (Account acc: Accs) {
        AccountMap.put(acc.Account_Custom_ID__c, acc);
    }


    for (Role__c r: trigger) {
        if (trigger.isInsert && r.Role__c.Custom_ID__c != null && AccountMap.get(r.Custom_ID__c) != null) {
            r.Account__c =  AccountMap.get(r.Custom_ID__c).Id;
        } else 
            if (trigger.isUpdate && r.Role__c.Custom_ID__c != null && && trigger.OldMap.get(r.Id).Custom_ID__c != r.Role__c.Custom_ID__c && AccountMap.get(r.Custom_ID__c) != null) {
                r.Account__c =  AccountMap.get(r.Custom_ID__c).Id;
            }

    }


}


Please use the above quick draft of trigger.