Skip to main content
i have parent and child and would like to udpate sum of a field from child collection to parent field its working fine for insert and udpate when i delete it throughs error where am i missing the code 

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

 

trigger quantityleft on Sample_Transaction__c (after insert,after update,after delete,after undelete) {

List<Sample_Lot__c> list_Account= new List<Sample_Lot__c>();

set<Id> set_Opportunity = new set<Id>();

for(Sample_Transaction__c objOpp: trigger.new){

set_Opportunity.add(objOpp.Parent_id__c);

}

Decimal Sum;

Sum=0;

for(Sample_Transaction__c sample_transaction : [SELECT id,Sample_Lot_ID__c, Transaction_Quantity__c FROM Sample_Transaction__c WHERE Parent_id__c = : set_Opportunity

]){

Sum+= sample_transaction.Transaction_Quantity__c;

for(Sample_Lot__c objAccount : [SELECT Id, Quantity_Left__c FROM Sample_Lot__c WHERE Id = : sample_transaction.Sample_Lot_ID__c]){

objAccount.Quantity_left__c = Sum ;

list_Account.add(objAccount);

update objAccount ;

}

}

}

 
1 answer
  1. Jun 8, 2017, 9:36 PM
    Hi Somasundaram, 

    Since, Your Code logic is same for Insert/Update and Delete, you are facing this problem. Consider using Trigger Context Variables. 

    if (Trigger.isInsert || Trigger.isUpdate) {

    // Your logic for Insert/Update

    }

    if (Trigger.isDelete) {

    // Your logic for Delete

    }

    if (Trigger.isUndelete) {

     

      // Your logic for Undelete

    }

    And Also Note the below details about availablity of a record in Trigger List during different events.

    | Events | trigger.Old | trigger.New |

    | -------------- |---------------| ------------:|

    | After Delete | Yes | No |

    | After Undelete | No | Yes |

    I believe, you are getting "Attempt to de-reference a null object "  Error because you are trying to access the deleted record from trigger.new in Trigger Delete event. or something like that. In a nut shell, Handle the code differently for different events with suitable trigger.New and trigger.Old lists.

    Hope it helps...

    Best,

    Nithesh.
0/9000