0

Below trigger is to sum the Amount of Contacts and display in the Account object. Trigger is working fine for insert, delete, and undelete. But while updating the Contact, I am getting the below error:

Apex trigger contactAmountSum caused an unexpected exception, contact your administrator: contactAmountSum: execution of AfterUpdate caused by: System.NullPointerException: Argument cannot be null.: Trigger.contactAmountSum: line 21, column 1

What might be the issue?

trigger contactAmountSum on Contact (after insert, after delete, after undelete, after update) {
  set<Id> accIdSet = new set<Id>();

  if(trigger.isinsert || trigger.isUpdate || trigger.Isundelete){
    for(Contact conObj: Trigger.new){
        if(Trigger.isInsert || Trigger.isUndelete || (conObj.Amounts__c != Trigger.oldMap.get(conObj.Id).Amounts__c || conObj.AccountId != Trigger.oldMap.get(conObj.Id).AccountId))
            accIdSet.add(conObj.AccountId);            
    }
  }    
  if(trigger.isUpdate || trigger.isDelete) {
    for(Contact conObj: Trigger.old){
        if(Trigger.isDelete || (conObj.Amounts__c != Trigger.newMap.get(conObj.Id).Amounts__c || conObj.AccountId != Trigger.newMap.get(conObj.Id).AccountId))
            accIdSet.add(conObj.AccountId);
    }
  }       
  List<Account> accList = [select id, Amounts__c, (Select Id, Amounts__c from contacts) from Account Where ID IN: accIdSet];    
  for(Account acc : accList){

    acc.Amounts__c = 0;
    for(Contact conObj : acc.contacts) {
        acc.Amounts__c += conObj.Amounts__c; // here getting null pointer exception
    }
  }
update accList;
}
0

conObj.Amounts__c seems to be null.

Can you try this one?

for(Contact conObj : acc.contacts) {
   if(conObj.Amounts__c != null){
       acc.Amounts__c += conObj.Amounts__c;
   }
}
| improve this answer | |
  • can u plz let me know how to get max, min of contacts in the same query used in trigger. – SFDC Student Oct 25 '19 at 10:51
0

If you want Max value and Min value, you can get by the below code.

acc.Amounts__c = 0;
acc.AmountsMax__c = 0;
acc.AmountsMin__c = 0;
for(Contact conObj : acc.contacts) {
   if(conObj.Amounts__c != null){
       acc.Amounts__c += conObj.Amounts__c;
       if(conObj.Amounts__c > acc.AmountsMax__c){
           acc.AmountsMax_c = conObj.Amounts__c;
       }
       if(conObj.Amounts__c < acc.AmountsMin__c){
           acc.AmountsMin_c = conObj.Amounts__c;
       } 
   }
}
| improve this answer | |
  • acc.AmountsMin_c showing as zero "0" value – SFDC Student Nov 7 '19 at 9:03

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.