0

My trigger

trigger testtrigger on Contact (after insert,after delete,after undelete){

    id accountId;
    id accountsid;
    for(Contact c:trigger.new){
        accountId=c.AccountId;
    }
    Integer count=[select count() from contact where AccountId=:accountId];

     if(trigger.isAfter && trigger.isInsert){
         for(Account a:[select number_of_contacts__c from Account where id=:accountId]){
            count=count+1;
             a.number_of_contacts__c=count;
             update a;
         }
     }

if(trigger.isDelete){

    for(Contact c:trigger.old){
        accountsId=c.AccountId;
    }
         for(Account a:[select number_of_contacts__c from Account where id=:accountsId]){
            count=count-1;
             a.number_of_contacts__c=count;
             update a;
         }
     }

    if(trigger.isAfter && trigger.isUndelete){
         for(Account a:[select number_of_contacts__c from Account where id=:accountId]){
            count=count+1;
             a.number_of_contacts__c=count;
             update a;
         }
     }

}

Error

Validation Errors While Saving Record(s) There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger testtrigger caused an unexpected exception, contact your administrator: testtrigger: execution of AfterDelete caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.testtrigger: line 5, column 1".

i am not able to delete contacts

  • This trigger is not written correctly and will fail if Contacts are involved from more than one Account. You need to bulkify the entire trigger. – David Reed May 16 '18 at 11:21
1

This is because you are trying to iterate trigger.new in delete case. Which you will get null and hence the exception.

SO you need to add trigger event check there

if(! trigger.isDelete) {
for(Contact c:trigger.new){
        accountId=c.AccountId;
    }
    Integer count=[select count() from contact where AccountId=:accountId];

     if(trigger.isAfter && trigger.isInsert){
         for(Account a:[select number_of_contacts__c from Account where id=:accountId]){
            count=count+1;
             a.number_of_contacts__c=count;
             update a;
         }
     }
}

Trigger Context Variables

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.