I have some code that is intended to work like the following: When the zipcode field on Accounts is inserted or updated, the triggers looks up whether the zip code is in a field called name on a custom object called DMA_Value__c. If the value is there the DMA_Value__c field on the DMA_Value__c object is returned to a field called DMA__c on the Opportunity object. My code is throwing a Invalide foreign key relationship for the line where I have Account.Opportunity. I'm guessing this means I need a map but I'm not sure where it should go. If your answer provides code could you please add an explanation so that I understand this better in the future? Please see the code below.
trigger UpdateDMAAccount on Account (before insert, before update) {
Set<String> BillingPostalCodes = new Set<String>();
for(Account a : trigger.new){
if(a.BillingPostalCode != null){
BillingPostalCodes.add(a.BillingPostalCode);
}
}
if(BillingPostalCodes.size() > 0){
//create Map of custom object records with Name (BillingPostalCode) as key
Map<String,DMA_Value__c> validBillingPostalCode = new Map<String,DMA_Value__c>();
for(DMA_Value__c obj : [SELECT Id, Name, DMA_Value__c FROM DMA_Value__c WHERE Name IN :BillingPostalCodes]){
validBillingPostalCode.put(obj.Name,obj);
}
for(Account a : trigger.new){
if((Trigger.isInsert || trigger.oldMap.get(a.Id).BillingPostalCode != a.BillingPostalCode) && validBillingPostalCode.containsKey(a.BillingPostalCode)){
a.opportunity.DMA__c = validBillingPostalCode.get(a.BillingPostalCode).DMA_Value__c;
}
else if(trigger.oldMap.get(a.Id).BillingPostalCode != a.BillingPostalCode && !validBillingPostalCode.containsKey(a.BillingPostalCode)){
//blank value if new BillingPostalCode does not match a record in the Map
a.Opportunity.DMA__c = null;
}
}
}
}
Id
. Just construct a new one with thatId
and you can update it.