I have a custom object in salesforce. Every record has many fields. One is a lookup field in which we select an opportunity from lookup. What we want is another lookup field: Account__c
which has to be automatically populated with account name of that respective opportunity.
In the code below, "After insert" is working but before update is not working properly.
trigger trigger_name on object__c (after insert, before update) {
List<object__c> listOfSfdcRecords =[SELECT Opportunity__r.AccountId,Opportunity__r.Account.Name FROM object__c WHERE ID IN :trigger.newMap.keySet()];
Map<String, Id> myMap = new Map<String, Id>();
for(object__c eachRec : listOfSfdcRecords){
System.debug(listOfSfdcRecords);
myMap.put(eachRec.Id, eachRec.Opportunity__r.AccountId);
}
if(trigger.isAfter){
List <object__c> updateList = new List <object__c>();
for(object__c eachSfdc: listOfSfdcRecords){
System.debug(eachSfdc.Opportunity__r.AccountId);
object__c sfdc = new object__c(Id = eachSfdc.Id);
sfdc.Test_Account__c = eachSfdc.Opportunity__r.AccountId;
updateList.add(sfdc);
}
update updateList;
}
if(trigger.isBefore){
for(object__c eachSfdc: trigger.new){
//System.debug('before update'+eachSfdc.Opportunity__r.AccountId);
System.debug('b4 update'+myMap.get(eachSfdc.id));
eachSfdc.Test_Account__c = myMap.get(eachSfdc.id);
}
}
}
Best Answer
You can do something like this. Basically you would need to get the opportunities of all the records that you're inserting / updating, get the associated accounts and then set the account values in the customOject's account__c field.