1

I created a trigger to associate a custom object to the account via an Opportunity record. However, my initial loop seems to fail to run. Can anyone spot what I'm missing?

trigger associatePMRtoMode on PMR__c (before insert, before update) {

    Set<ID> AccountIds = new Set<ID>();
    Map<ID,ID> ACC_PMR = new Map<ID,ID>();

    for (PMR__c PMR :Trigger.new){
        AccountIds.add(PMR.Opportunity__r.AccountId);
        ACC_PMR.put(PMR.Opportunity__r.AccountId, PMR.Id);
    }

    System.debug('AccountIds = ' + AccountIds);
    System.debug('ACC_PMR = ' + ACC_PMR);
}

1 Answer 1

5

You're trying to reach through the Opportunity relationship, but triggers don't pull that data in directly. You'd have to pull them in a separate query.

Here is an example of how to achieve what you're after (fair warning, hand written code here):

Set<ID> AccountIds = new Set<ID>();
Set<Id> OppIds = new Set<Id>();
Map<ID,ID> ACC_PMR = new Map<ID,ID>();

for (PMR__c PMR :Trigger.new){
    OppIds.add(PMR.Opportunity__c);
}

// this is bulkified because it runs one query for all PMR objects
Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([select AccountId from Opportunity where Id in : OppIds]);
for(PMR__c PMR : trigger.new) {
    // grab the opportunity by id from the map using the id from the PMR, and grab the accountId
    AccountIds.add(oppMap.get(PMR.Opportunity__c).AccountId);
    // use the same technique to put it into your map
    ACC_PMR.put(oppMap.get(PMR.Opportunity__c).AccountId, PMR.Id);
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .