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
DJPDJP 

salesforce trigger to update account id on custom object

Hello,
I have custom object Location__c and custom field on Account.SAP_BP_ID__c. The custom Object Location__c has fields AccountID__c and SAP_ID__c. Location__c will be populated via API in back ground. Location__c.AccountID__c has lookup relationship with Account. I need a trigger to update the AccountID__C on Location__c object with Account.ID whenever a new location is created. 
Update Location__c.AccountID__c where Location__c.SAP_BPID__c = Account.SAP_ID__c
and Location__c.AccountID__c has lookup relationship with Account (sorry to repeat)

Thanks
Dinesh
Best Answer chosen by DJP
Syed Insha Jawaid 2Syed Insha Jawaid 2
Hi Dinesh

Please use this following code block : 

TRIGGER on <LOCATION> beforeInsert { 
Set < String > setOfSAPIds = new Set < String >();
for(Location__c location : triggerNew) {
if(location.SAP_BPID__c != null)
setOfSAPIds.add(location.SAP_BPID__c);
}

if(setOfSAPIds.isEmpty())
 return;

Map < String, String > mapOfSAPidVsAccountId = new Map < String, String >();  
for(Account acc : [SELECT Id,SAP_ID__c from Account where SAP_ID__c IN : setOfSAPIds]) {
 mapOfSAPidVsAccountId.put(acc.SAP_ID__c,acc.Id);
}

if(mapOfSAPidVsAccountId.values().isEmpty())
 return;

for(Location__c location : triggerNew) {
if(location.SAP_BPID__c != null) {
location.AccountID__c = mapOfSAPidVsAccountId.get(location.SAP_BPID__c);
 }
}
}

TriggerNew has all the updated value, you can debug to check.

Cheers!!!!
 

All Answers

Syed Insha Jawaid 2Syed Insha Jawaid 2
Hi Dinesh

Please use this following code block : 

TRIGGER on <LOCATION> beforeInsert { 
Set < String > setOfSAPIds = new Set < String >();
for(Location__c location : triggerNew) {
if(location.SAP_BPID__c != null)
setOfSAPIds.add(location.SAP_BPID__c);
}

if(setOfSAPIds.isEmpty())
 return;

Map < String, String > mapOfSAPidVsAccountId = new Map < String, String >();  
for(Account acc : [SELECT Id,SAP_ID__c from Account where SAP_ID__c IN : setOfSAPIds]) {
 mapOfSAPidVsAccountId.put(acc.SAP_ID__c,acc.Id);
}

if(mapOfSAPidVsAccountId.values().isEmpty())
 return;

for(Location__c location : triggerNew) {
if(location.SAP_BPID__c != null) {
location.AccountID__c = mapOfSAPidVsAccountId.get(location.SAP_BPID__c);
 }
}
}

TriggerNew has all the updated value, you can debug to check.

Cheers!!!!
 
This was selected as the best answer
DJPDJP
Thank you very much.