0

I need help creating a method that queries the AccountContactRelation object and throws an error when an Opp is created without having an AccountContactRelation between its Primary Contact and Account. I have created the method below and works successfully, but the code is not bulkified, it is just taking one record at the time instead the whole trigger.new. I have created 2 maps relating Opp with Account and Opp with Contact, but the result are not accurate since I have to query ACRs that are related to the Account and Contact for each Opportunity.

This method is a 'Before Insert' event

    public static void checkVestingScope(Opportunity opp){

    List<AccountContactRelation> acr = New List<AccountContactRelation>([Select Id from AccountContactRelation where AccountId =:opp.AccountId and ContactId =:opp.Borrower_Contact__c]);

    if(acr.size() == 0){

        //check for unit test
        if(Test.isRunningTest()){

            String memo = 'Error runs here';
            System.Debug(memo);

        }else{
            //throw vesting error
            throw new applicationException('Error! Vesting Account (account name) and Primary Guarator (borrower contact) must have a relationship in order to save.');
        }

    }

}
0

First, you want to pass a collection into your trigger handler method: handler.checkVestingScope(Trigger.new) results in public static void checkVestingScope(list <Opportunity> listOpportunities).

Then add the Ids into a list:

list <Id> acctIds = new list <Id>();
list <Id> contIds = new list <Id>();
for(Opportunity opp : listOpportunities){
   acctIds.add(opp.AccountId);
   contIds.add(opp.Borrower_Contact__c); 
}

Check if the lists are not empty/null, and then modify your query:

List<AccountContactRelation> acr = New List<AccountContactRelation>([Select Id from AccountContactRelation where AccountId IN:acctIds and ContactId =:contIds]);

Here is a link on how you bulkify a trigger: General trigger bulkification - best practices

|improve this answer|||||
  • Yes, that was the first thing I tried, but the fact that the Ids are in both lists doesn't mean that they are related to the same opportunity. We use multiple Accounts in our org. Thanks for the help – Alex Cortes Aug 23 '19 at 13:23
  • I think then you ask a different question. – user40501 Aug 23 '19 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.