+ Start a Discussion
Somasundaram S 1Somasundaram S 1 

how to handle this while delete the record

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){
        Decimal Sum;

  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 ;


 update objAccount ;



Nithesh NNithesh N
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...