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
Michael Hedrick 2Michael Hedrick 2 

Apex Trigger Firing inconsistently

Hello I have the following Trigger that is not firing consistently.  When a user creates or updates a Contact and the Primary Checkbox = true the trigger should fire which copies the email address on the Contact to the assocuated Account record. 
All of the Contacts are associated to an Account.
Here is the trigger and test class.  Coverage is 92%.  Trued to use before trigger but casues the Test to fail. 
Trigger:
trigger DealerPrimaryContact on Contact ( after insert, after update) {
Set<Id> DealerAccIdSet=new Set<Id>();

   for(Contact cont:Trigger.new)
   {
     if(cont.AccountId !=null && cont.Primary__c == True )
     {

        DealerAccIdSet.add(cont.AccountId); 
     }
   }

   if(!DealerAccIdSet.isEmpty()){

      List<Account> DealerAccListToUpdate=new List<Account>();

        for(Account acc: [SELECT id,(SELECT id,email FROM Contacts where Primary__c = True ) FROM Account WHERE Partner_Type__c = 'Dealer' And Id IN :DealerAccIdSet] ){

         acc.Primary_Contact_Email_Address__c=acc.Contacts[0].email;

          DealerAccListToUpdate.add(acc);

       }

       if(!DealerAccListToUpdate.isEmpty()){

         try{

            Update DealerAccListToUpdate;

         }Catch(DmlException de ){

           System.debug(de);

         }

       }

   }
}

Test Class:
@isTest (SeeAllData = false)
public class TestDealerPrimaryContact {
    @isTest    
    public static void DealerPrimaryTestClass() 
    {
 
        Account a = new Account();
            a.Name= 'Test Dealer Account';
            a.Type= 'Dealer / Distributor';
            a.Partner_Type__c = 'Dealer';
            a.Tier__c = 'Stocking Dealer';
            a.Status__c = 'Active';     
            a.RecordTypeId = '012j0000000cfvw';
            a.Primary_Contact_Email_Address__c ='';
            insert a;
    
       Contact con = new Contact();
            con.Contact_Types__c= 'Employee';
            con.FirstName= 'Tester';
            con.LastName= 'testy';
            con.Email='test@gmail.com';
            con.Primary__c = false;
            con.Phone = '111-111-2222';  
           con.Primary__c=true;
         
               
        test.startTest(); 
        
       //   insert a;
          insert con;
          con.AccountId= a.Id;
          a.Primary_Contact_Email_Address__c =con.Email  ;
          update con;
          update a;
        test.stopTest();        
       
    }

}

Thanks,
M
Best Answer chosen by Michael Hedrick 2
Kai Herng LauKai Herng Lau
can you try to disable all the automations? I suspect they causing the problem

All Answers

Kai Herng LauKai Herng Lau
Hi Micheal,

Your code look ok, I don't think salesforce trigger is inconsistent, but there is one thing it may cause confusion which is in line 20

acc.Primary_Contact_Email_Address__c=acc.Contacts[0].email;

Imagine if my account record have 3 childs contact records and all of the fulfill the condition Contact.Primary__c = true. Theaccount.primary_contact_email_address__c will alway equal to first contact's email. Up to this point, if you inconsistent mean the account.primary_contact_email_address__c is showing the similar email address. It may because of this problem.

Hope this help
Michael Hedrick 2Michael Hedrick 2
Kai,
Thank you for the reply. And yes this could happen but we rarely have more than a single contact on these records.  So do you see anything in the code that would cause the trigger not to work when there is only a single contact record with the primary_c checkbox set to true?
Thanks,
Michael
Kai Herng LauKai Herng Lau
Hi Micheal,

I don't see anything will cause the code didn't run, but do you mind to run some test to verify if there is possible issue exist

First: How is the Contact record get updated or created? What I mean here is are they get created/updated by others automation jobs or it is manual steps

Second: To check if the DealerAccIdSet(line 10) has return value
Step: Add System.debug('****RUN HERE: ' + DealerAccIdSet); at line 11 & open your developer console the view the log

Third: Do you have any validation rules, trigger, workflow or process builder in account object? It may cause conflict when your trigger try to update the Account record. You also can use the developer console to view the log

Hope those step help you to identify the problem.
Michael Hedrick 2Michael Hedrick 2
Ok I added some debugging as you recommended:
trigger DealerPrimaryContact on Contact (before insert, after insert, after update) {
Set<Id> DealerAccIdSet=new Set<Id>();

   for(Contact cont:Trigger.new)
   {
     if(cont.AccountId !=null && cont.Primary__c == True )
     {

        DealerAccIdSet.add(cont.AccountId); 
        System.debug('****RUN HERE: ' + DealerAccIdSet); 
     }
   }

   if(!DealerAccIdSet.isEmpty()){

      List<Account> DealerAccListToUpdate=new List<Account>();

        for(Account acc: [SELECT id,(SELECT id,email FROM Contacts where Primary__c = True ) FROM Account WHERE Partner_Type__c = 'Dealer' And Id IN :DealerAccIdSet] ){

         acc.Primary_Contact_Email_Address__c=acc.Contacts[0].email;

          DealerAccListToUpdate.add(acc);
     System.debug('****Add : ' + acc);
       }

       if(!DealerAccListToUpdate.isEmpty()){

         try{

            Update DealerAccListToUpdate;

         }Catch(DmlException de ){

           System.debug(de);

         }

       }

   }
}
 Here are the results:
14:25:12:261 USER_DEBUG [10]|DEBUG|****RUN HERE: {xxxxxxxxxxxxxxxxxxxxx}  - good, this is the right Account
14:25:12:268 USER_DEBUG [23]|DEBUG|****Add : Account:{Id=xxxxxxxxxxxxxx, Primary_Contact_Email_Address__c=test@gmail.com}  -- correct account and email address
14:25:12:576 USER_DEBUG [34]|DEBUG|System.DmlException: Update failed. First exception on row 0 with id 001j000000KntdtAAB; first error: FIELD_INTEGRITY_EXCEPTION, system.security.NoDataFoundException: ORA-20001:

No Data? What?

Should this part of the code be in the try?   acc.Primary_Contact_Email_Address__c=acc.Contacts[0].email;

Thanks for all your help.
 
Kai Herng LauKai Herng Lau
Hi

Can you try to update the debug log in line 34 to:
System.debug(de.getStackTraceString());

Just to double confrim, do you have any other automation in account it will fire when the account get updated at line 30? 
 
Michael Hedrick 2Michael Hedrick 2
Updates Trigger debug log: System.debug(de.getStackTraceString()); at line 34

20:19:36:275 USER_DEBUG [10]|DEBUG|****RUN HERE: {001j000000KntdtAAB}
20:19:36:282 USER_DEBUG [19]|DEBUG|****email: tester@gmail.com
20:19:36:282 USER_DEBUG [23]|DEBUG|****Add : Account:{Id=00000000000AAB, Primary_Contact_Email_Address__c=email: tester@gmail.com}
20:19:36:570 USER_DEBUG [34]|DEBUG|Trigger.DealerPrimaryContact: line 30, column 1

I have validation rules, triggers, and work flows on the Account object.  But not specificallty based on where the Partner_Type__c = 'Dealer'  & Primary__c = True

What is the 'getStackTraceString' telling us?

Thanks,
M
 
Kai Herng LauKai Herng Lau
Hi Micheal,

I'm not sure what is the problem yet but I suspect it maybe the multiple update course the confliction in Account object. The getStackTraceString is used to show where is the line causing the problem. I was hoping it will show us if we have other trigger causing the problem.

Here I have 2 suggestion for you to identify the problem:

1st is to understand all you automation and find out the problem.
2nd, the easy way. Turn off your automation (validation rules, triggers and workflow) one by one or all and try to run the update to identify which of the automation causing the conflict with your current trigger.

Hope my suggestion help
Michael Hedrick 2Michael Hedrick 2
The field Primary Contact Email Address is a type Email.  Not sure if this mattered.
Kai Herng LauKai Herng Lau
I don't think so, because your acc.Contacts[0].email also is the email field and I have try copy your code into a test instance, it will run without any error
Michael Hedrick 2Michael Hedrick 2
Yes, I do not get any errors it just does not update the field on the Account.  Some Accounts have no issue.
Could it be my select statement?  Should I be selecting the AccountId on the Contact record?
Kai Herng LauKai Herng Lau
The query run fine as you can see it is actually getting the results. I believe is the data or the conflict of your automation. You can give it a try, if you think it may work
Michael Hedrick 2Michael Hedrick 2
Ok I chnaged the trigger to 'before update' and 'before insert' and it seems to be working.  I will need to see if I can do a mass update but could I have simply had the incorrect action?
Michael Hedrick 2Michael Hedrick 2
I just noticed something.  If I edit and save the account.  Then go and edit/save the Contact record the trigger updates.
Not sure what that is.
Kai Herng LauKai Herng Lau
can you try to disable all the automations? I suspect they causing the problem
This was selected as the best answer
Michael Hedrick 2Michael Hedrick 2
I will give that a try but I have looked at this enough for today......